din*_*Kid 5 java collections for-loop list
我有一个User
带有a String
和int
属性的简单类.
我想以这种方式添加两个用户列表:
像这样:
List1: { [a:2], [b:3] }
List2: { [b:4], [c:5] }
ResultList: {[a:2], [b:7], [c:5]}
Run Code Online (Sandbox Code Playgroud)
User
定义:
public class User {
private String name;
private int comments;
}
Run Code Online (Sandbox Code Playgroud)
我的方法:
public List<User> addTwoList(List<User> first, List<User> sec) {
List<User> result = new ArrayList<>();
for (int i=0; i<first.size(); i++) {
Boolean bsin = false;
Boolean isin = false;
for (int j=0; j<sec.size(); j++) {
isin = false;
if (first.get(i).getName().equals(sec.get(j).getName())) {
int value= first.get(i).getComments() + sec.get(j).getComments();
result.add(new User(first.get(i).getName(), value));
isin = true;
bsin = true;
}
if (!isin) {result.add(sec.get(j));}
}
if (!bsin) {result.add(first.get(i));}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
但它在列表中添加了很多东西.
这最好通过toMap
收集器完成:
Collection<User> result = Stream
.concat(first.stream(), second.stream())
.collect(Collectors.toMap(
User::getName,
u -> new User(u.getName(), u.getComments()),
(l, r) -> {
l.setComments(l.getComments() + r.getComments());
return l;
}))
.values();
Run Code Online (Sandbox Code Playgroud)
Stream<User>
via Stream.concat
.toMap
收集器来合并碰巧具有相同性质的用户Name
并获得结果Collection<User>
.如果你严格要一个List<User>
然后将结果传递给ArrayList
构造函数,即List<User> resultSet = new ArrayList<>(result);
感谢@davidxxx,您可以直接从管道收集到列表并避免创建中间变量:
List<User> result = Stream
.concat(first.stream(), second.stream())
.collect(Collectors.toMap(
User::getName,
u -> new User(u.getName(), u.getComments()),
(l, r) -> {
l.setComments(l.getComments() + r.getComments());
return l;
}))
.values()
.stream()
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
114 次 |
最近记录: |