Java 8流-通过比较两个列表进行过滤

时间:2019-09-27 12:36:05

标签: java java-8 java-stream

我有2个彼此不同的列表

public class App1{
    private String name;
    private String city;

    // getter setter

    // constructors
}

public class App2{
    private String differentName;
    private String differentCity;
    private String someProperty1;
    private String someProperty2;

    // getter setter

    // constructors
}

List<App1> app1List = new ArrayList<>();
app1List.add(new App1("test1","city1"));
app1List.add(new App1("test2","city2"));
app1List.add(new App1("test3","city3"));
app1List.add(new App1("test4","city4"));

List<App2> app2List = new ArrayList<>();
app2List.add(new App2("test2","city2"));
app2List.add(new App2("test3","city3"));

如您所见,App1和App2类是2个不同的Pojo,它们具有不同的属性名称,但是名称,city和differentName,differentCity属性分别持有的内容/值是相同的,即test1,test2,test3和city1,city2等

现在我需要过滤app1List来比较其他列表中的名称和城市,即不存在的app2List。

最终输出应为

app1List.add(new App1("test1","city1"));
app1List.add(new App1("test4","city4"));

最简单的方法是多次循环其他列表之一,这是我试图避免的。 Java 8流中是否有任何方法无需循环多次?

3 个答案:

答案 0 :(得分:3)

您可以使用noneMatch操作,例如:

List<App1> result = app1List.stream()
        .filter(app1 -> app2List.stream()
                .noneMatch(app2 -> app2.getDifferentCity().equals(app1.getCity()) &&
                        app2.getDifferentName().equals(app1.getName())))
        .collect(Collectors.toList());

这假设name进行时cityfilter的组合都匹配。

答案 1 :(得分:0)

您需要在override类中使用equals App2方法:

public class App2{
    private String differentName;
    private String differentCity;
    private String someProperty1;
    private String someProperty2;

    // getter setter

    // constructors

    @Override
    public boolean equals(Object obj) {
       App2 app2 = (App2) obj;
       return this.differentName.equals(app2.getDifferentName()) && this.differentCity.equals(app2.getDifferentCity());
    }
}

,然后您可以像这样使用list1上的流:

app1List = app1List.stream()
                .filter(a-> !app2List.contains(new App2(a.getName(),a.getCity())))
                .collect(Collectors.toList());

输出:

[App1{name='test1', city='city1'}, App1{name='test4', city='city4'}]

答案 2 :(得分:0)

假设您要同时匹配名称和城市,则可以创建一个将对象映射到的函数,例如:

public static Integer key(String name, String differentCity) {
    return Objects.hash(name, differentCity);
}

然后使用该密钥创建一组密钥,以使用noneMatch对其进行过滤,例如:

Set<Integer> sieve = app2List.stream()
        .map(app2 -> key(app2.differentName, app2.differentCity)).collect(Collectors.toSet());

List<App1> result = app1List.stream().filter(app1 -> sieve.stream()
        .noneMatch(i -> i.equals(key(app1.name, app1.city))))
        .collect(Collectors.toList());

System.out.println(result);

输出

[App1{name='test1', city='city1'}, App1{name='test4', city='city4'}]

此方法的复杂度为O(n + m),其中nm是列表的长度。