我正在查看一些旧代码,在其中对元素进行分组。看起来或多或少是这样的:
Map<Long,List<Items>> groupedItems = ...
for (long groupid : groups){
for (Item item :items){
if (isGroupAccepting(item.getId(),groupid) || groupid == item.getGroup()) {
groupedItems.get(groupid).add(item);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我计划使用流API中的分组替换它,但是我遇到了麻烦。对于我的第二个条件,它工作正常,但是如何处理第一个条件,即应将项添加到接受此类项的每个组中?实际上有可能吗,还是我在这里与失落的原因作斗争?
我需要从一个给定的字符串创建一个数字字符串的ascii值。我的字符串仅包含大写的AZ字符。
目前,我有:
String example = "STRING";
List<Integer> list = example.chars()
.mapToObj(item -> (int) item)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
输出: [83, 84, 82, 73, 78, 71]
比我做的:
String asciiString = list.stream()
.map( n -> n.toString() )
.collect( Collectors.joining( "" ) );
Run Code Online (Sandbox Code Playgroud)
输出: 838482737871
有更有效的方法吗?可能只有一个流?
我正在尝试从我的LinkedHashMap中过滤出不必要的null值。但是,实际上并没有删除这些值。
变量声明
Map<String,Object> dataDictionary = new LinkedHashMap<>();
Run Code Online (Sandbox Code Playgroud)
使用filter方法后,在sysout.print(dataDictionary)返回的内容的一小部分。
[industryCodes=<null>,regionCodes=<null>,andKeywords=false,id=
<null>,resultsPerPage=20,keywords=<null>,omitKeywords=<null>}
Run Code Online (Sandbox Code Playgroud)
Java代码
dataDictionary= dataDictionary.entrySet()
.stream()
.filter(entry -> entry.getValue()!=null)
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)
期望空值及其键将被删除,但这似乎没有发生。
我有一堂课
class Person {
public List<BaseballPlayer> baseballPlayers;
public List<MmaFighter> mmaFighters;
public List<RugbyPlayer> rugbyPlayers;
}
Run Code Online (Sandbox Code Playgroud)
在每个对象播放器中,其id都有String属性。我正在尝试收集列表中的所有ID
List<String> baseballPlayersIds = person.baseballPlayers.stream()
.map(s -> s.getId()).collect(Collectors.toList());
List<String> mmaFightersIds = person.mmaFighters.stream()
.map(s -> s.getId()).collect(Collectors.toList());
List<String> rugbyPlayersIds = person.rugbyPlayers.stream()
.map(s -> s.getId()).collect(Collectors.toList());
baseballPlayersIds.addAll(mmaFightersIds);
baseballPlayersIds.addAll(rugbyPlayersIds);
Run Code Online (Sandbox Code Playgroud)
现在,我试图通过使用Stream.concat()简化事情并改善逻辑
Stream<List<BaseballPlayer>> baseballPlayersIdsStream = Stream.of(person.baseballPlayers);
Stream<List<MmaFighter>> mmaFightersIdsStream = Stream.of(person.mmaFighters);
Stream<List<RugbyPlayer>> rugbyPlayersIdsStream = Stream.of(person.rugbyPlayers);
Stream<List<? extends Object>> personStream = Stream.concat(baseballPlayersIdsStream, Stream.concat(mmaFightersIdsStream, rugbyPlayersIdsStream));
Run Code Online (Sandbox Code Playgroud)
但我无法确定是否应该对这3个流中出现的新流类型使用泛型?还尝试为所有3个类创建父类,以在流diamand中代替Object使用。这个personStream有疑问。
我想使用Java8 Stream转换一些逻辑。我们应该如何修改代码?
public boolean isBFOrder(final BFReturn pReturnRequest) {
ArrayList<BFReturnShip> shipGroupList =pReturnRequest.getShipGroupList();
Boolean bfOrder = false;
for(BFReturnShip bfReturnShip : shipGroupList) {
if(bfReturnShip.getModeOfReturn().equals(TYPE)) {
bfOrder = true;
} else {
return false;
}
}
return bfOrder;
}
Run Code Online (Sandbox Code Playgroud) 我正在实现一个流,在其中使用集合listOfFoo来获取该列表中所有项目的ID,并使用它们来获取Bar实例的值。
我想确保此方法在酒吧列表上没有任何项目的情况下将抛出ResourceNotFoundException,尽管在当前状态下它会检查列表酒吧是否为null,而不是,因为它包含一个空列表。
您能帮我一下,并提出一些解决方案吗?
List<Bar> bars = Optional.ofNullable(
listOfFoos.stream()
.map(Foo::getId)
.map(fooId -> service.getBars(fooId))
.filter(Objects::nonNull)
.collect(Collectors.toList()))
.orElseThrow(() -> new ResourceNotFoundException(Bar.class, OBJECT_NULL));
Run Code Online (Sandbox Code Playgroud) 新手问题。我有一个原始的豆从数据库逐行
public class DataBean {
private Integer employeeId;
private String org;
private String comments;
// + Constructors, getters/setters
}
Run Code Online (Sandbox Code Playgroud)
我需要将其映射到具有多个Org的另一个Bean,这些组织按Employee ID分组到一个列表中。雇员ID的唯一组织可以是多个;“评论”字段必定是相同的。
public class CustomDataBean {
private Integer employeeId;
private List<String> orgs;
private String comments;
// + Constructors, getters/setters
}
Run Code Online (Sandbox Code Playgroud)
努力入门。想到groupingBy了以下内容,但返回了Map,而我没有建立子列表。
Map<Integer, List<String>> temp = origData.stream().collect(
Collectors.groupingBy(OrigBean::getEmployeeId,
/* 2nd param? */ .. ))
Run Code Online (Sandbox Code Playgroud)
我的目标是转变List<CustomDataBean>。
我有一个类似的场景:
public class A {
private String id;
@ManyToMany
private Set<B> bSet;
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
和
public class B {
private String id;
// other attributes
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
A当我有B使用stream()API 的实例时,如何查找实例?我正在尝试类似的东西:
public A findAFromB(B b) {
List<A> aList = aService.findAll();
Optional<A> matchingObject = aList.stream().filter({find a where a.getBSet().contains(b)}).getA();
return (A) matchingObject.get();
}
Run Code Online (Sandbox Code Playgroud)
如何正确编写此过滤器?
我是Java 8的新手,我需要重写一段旧代码以实现新的算法。任务是过滤每个列表具有最大速度的对象。列表嵌套在地图内部:道路的根地图,其中包含路段的地图,每条路段的地图都包含一系列对象,每个对象描述一个时间间隔的测得速度。我需要找到每个列表的所有最大速度。
我发现以下链接看起来像我的问题,但是我无法适应它们,而且我不确定我的尝试能否正确解决我的问题。
Java 8筛选器映射<String,List <Employee >>
这是我用来写我的例子的代码
Map<String, Map<String, Employee>> employeeMap =
employeeMap.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey,
e -> e.getValue().entrySet().stream()
.filter(emp -> !emp.getValue().getState().equals("MI"))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue))));
for(Car car : cars) {
for (Engine engine : car.getEngines()) {
for (Part part : engine.getParts()) {
// ...
}
}
}
cars.stream()
.flatMap(car -> car.getEngines().stream())
.flatMap(engine -> engine.getParts().stream())
.forEach(part -> { ... });
Run Code Online (Sandbox Code Playgroud)
这是我的结果代码
Map<Integer, Map<Integer, List<PartialSpeed>>> speedsPerRoadPerSegment;
ArrayList<PartialSpeed> maxSpeedPerSegment = new ArrayList<PartialSpeed>();
speedsPerRoadPerSegment.entrySet().stream()
.forEach(road-> road.getValue().entrySet()
.stream()
.forEach(segment ->
{
Optional<PartialSpeed> result …Run Code Online (Sandbox Code Playgroud) Is it possible with Java stream API to duplicate items a few times?
For instance let's say we have a list of orders where each order has a product code and quantity. I want to get a list of product codes which contains n copies of the given code where n is the quantity.
When I got 2 orders ("product1" : 3x, "product2": 2x) I want in result a list like this: ("product1", "product1", "product1", "product2", "product2")
Is there a …
java ×10
java-stream ×10
java-8 ×6
collections ×2
exception ×1
lambda ×1
optional ×1
pojo ×1
spring ×1