添加两个自己类型的列表

din*_*Kid 5 java collections for-loop list

我有一个User带有a Stringint属性的简单类.

我想以这种方式添加两个用户列表:

  • 如果String等于那么应该添加数字,那将是它的新值.
  • 新列表应包括具有适当值的所有用户.

像这样:

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)

但它在列表中添加了很多东西.

Ous*_* D. 5

这最好通过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)