我有一个简单的User
类,它有一个String
和一个int
属性。
我想以这种方式添加两个用户列表:
- 如果字符串相等,则应将数字相加,并成为其新值。
- 新列表应包括所有具有适当值的用户。
像这样:
List1: { [a:2], [b:3] }
List2: { [b:4], [c:5] }
ResultList: {[a:2], [b:7], [c:5]}
User
定义:
public class User {
private String name;
private int comments;
}
我的方法:
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;
}
但它将许多东西添加到了列表中。
.values().stream().collect(toList())
来避免定义额外的变量。 - davidxxxUser
内部的一个方法中,然后使用管道中的方法引用调用它,这将导致更好的可读性并避免开销。例如,该方法将如下所示:public User merge(User other) { setComments(getComments() + other.getComments()); return this; }
然后在上面的合并函数的位置使用User::merge
。 - Ousmane D..collect(groupingBy(User::getName, summingInt(User::getComments)))
,然后将每个条目映射到一个User
对象。;-) - Ousmane D.