Java8流-比较两个List的对象值并将值添加到新的List?

时间:2019-07-29 11:04:30

标签: java arraylist lambda java-8 java-stream

我有两个包含此类对象的列表:

cypress open --project test/cypress

我想按public class SchoolObj { private String name; private String school; public SchoolObj() { this(null, null); } public SchoolObj(String nameStr, String schoolStr) { this.setName(nameStr); this.setSchool(schoolStr); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getSchool() { return this.school; } public void setSchool(String school) { this.school = school; } @Override public String toString() { return this.getName() + ' ' + this.getSchool(); } } name比较这两个列表中的对象。如果它们相等,则需要创建一个新的school,其中包含在两个列表中都找到的List对象。

我知道我们可以使用两个SchoolObj循环,并且可以通过下面的for方法来实现。

我的问题是,如何用Java流完成同一件事?

我尝试使用下面的createSharedListViaLoop,但是它没有按预期工作。

createSharedListViaStream

2 个答案:

答案 0 :(得分:1)

让我们遍历代码的每个部分。首先,createSharedListViaStream

public static List<SchoolObj> createSharedListViaStream(List<SchoolObj> listOne, List<SchoolObj> listTwo)
{
    // We create a stream of elements from the first list.
    List<SchoolObj> listOneList = listOne.stream()
    // We select any elements such that in the stream of elements from the second list
    .filter(two -> listTwo.stream()
    // there is an element that has the same name and school as this element,
        .anyMatch(one -> one.getName().equals(two.getName()) 
            && two.getSchool().equals(one.getSchool())))
    // and collect all matching elements from the first list into a new list.
    .collect(Collectors.toList());
    // We return the collected list.
    return listOneList;
}

运行完代码后,它会完全按照您想要的去做。现在,让我们看一下createSharedListViaLoop

public static List<SchoolObj> createSharedListViaLoop(List<SchoolObj> listOne, List<SchoolObj> listTwo)
{
    // We build up a result by...
    List<SchoolObj> result = new ArrayList<SchoolObj>();
    // going through each element in the first list,
    for (SchoolObj one : listOne)
    {
    // going through each element in the second list,
        for (SchoolObj two : listTwo)
        {
    // and collecting the first list's element if it matches the second list's element.
            if (one.getName().equals(two.getName()) && one.getSchool().equals(two.getSchool()))
            {
                result.add(one);
            }
        }
    }
    // We return the collected list
    return result;
}

到目前为止,太好了...对吗?实际上,您在createSharedListViaStream中的代码从根本上是正确的;相反,您的createSharedListViaLoop可能会导致输出差异。

请考虑以下输入设置:
List1 = [SchoolObj("nameA","SchoolX"), SchoolObj("nameC","SchoolZ")]
List2 = [SchoolObj("nameA","SchoolX"), SchoolObj("nameA","SchoolX"), SchoolObj("nameB","SchoolY")]

此处,createSharedListViaStream将返回出现在两个列表中的第一个列表的唯一元素:SchoolObj("nameA","SchoolX")。但是,createSharedListViaLoop将返回以下列表:[SchoolObj("nameA","SchoolX"),SchoolObj("nameA","SchoolX")]。更准确地说,createSharedListViaLoop将收集正确的对象,但是它将收集两次。基于与createSharedListViaStream的输出比较,我怀疑这是createSharedListViaLoop的输出“不正确”的原因。

createSharedListViaLoop进行此复制的原因是由于其内部for循环没有终止。尽管我们遍历第一个列表的所有元素以检查第二个列表中是否存在这些元素,但是找到一个匹配项即可将元素添加到结果中。我们可以通过将内部循环更改为以下内容来避免添加多余的元素:

for (SchoolObj one : listOne)
    {
    for (SchoolObj two : listTwo)
    {
        if (one.getName().equals(two.getName()) && one.getSchool().equals(two.getSchool()))
        {
            result.add(one);
            break;
        }
    }
}

此外,如果您不想在列表中重复对象(按内存中的位置),则可以像这样使用distinct

List<SchoolObj> result = ...;
result = result.stream().distinct().collect(Collectors.toList());

作为最后的警告,在以下情况下,以上内容将使结果与众不同:

List<SchoolObj> list = new ArrayList<>();
SchoolObj duplicate = new SchoolObj("nameC", "schoolD");
listOne.add(duplicate);
listOne.add(duplicate);
list.stream().distinct().forEach(System.out::println); 
// prints:
// nameC schoolD

但是,除非您为SchoolObj覆盖equals方法,否则它在以下情况下将不起作用:

List<SchoolObj> list = new ArrayList<>();
listOne.add(new SchoolObj("nameC", "schoolD"));
listOne.add(new SchoolObj("nameC", "schoolD"));
list.stream().distinct().forEach(System.out::println); 
// prints (unless Object::equals overridden)
// nameC schoolD
// nameC schoolD

答案 1 :(得分:0)

如果包含在另一个列表中,则可以在一个列表中进行过滤,然后收集。

List<SchoolObj> listCommon = listTwo.stream()
                                         .filter(e -> listOne.contains(e)) 
                                         .collect(Collectors.toList());

您需要重写equals()类中的SchoolObj方法。 contains()方法,您将使用equals()方法来评估两个对象是否相同。

@Override
public boolean equals(Object o) {
    if (!(o instanceof SchoolObj))
        return false;
    SchoolObj n = (SchoolObj) o;
    return n.name.equals(name) && n.school.equals(school);
}

但是更好的解决方案是对一个列表使用Set并在另一个列表中进行过滤以收集Set中是否包含。 Set#contains的O(1)更快。

Set<SchoolObj> setOne = new HashSet<>(listOne);
List<SchoolObj> listCommon = listTwo.stream()
                                     .filter(e -> setOne.contains(e)) 
                                     .collect(Collectors.toList());

对于hashCode(),您还需要重写equals()类中的SchoolObj方法和Set#contains类中的name。(假设school@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + name.hashCode(); result = prime * result + school.hashCode(); return result; } 可以' t为空)

{{1}}

Here,您将获得如何更好地覆盖equals和hashCode的详细信息