使用java 8迭代和过滤两个列表

Aru*_*hot 12 java filter

我想迭代两个列表并获得新的过滤列表,其中的值将不存在于第二个列表中.有人可以帮忙吗?

我有两个列表 - 一个是字符串列表,另一个是MyClass对象列表.

List<String> list1;
List<MyClass> list2;

MyClass {

    MyClass(String val)
    {
        this.str = val;
    }

     String str;
     ...
     ...
}
Run Code Online (Sandbox Code Playgroud)

我希望基于以下方式过滤字符串列表 - >检查其值不存在的元素(abc)的第二个列表list1.

List<String> list1 = Arrays.asList("abc", "xyz", "lmn");

List<MyClass> list2 = new ArrayList<MyClass>();

MyClass obj = new MyClass("abc");
list2.add(obj);
obj = new MyClass("xyz");
list2.add(obj);
Run Code Online (Sandbox Code Playgroud)

现在我想要新的过滤列表 - >将有值=>"lmn".即不存在list2于其元素所在的值list1.

Ash*_*eze 20

// produce the filter set by streaming the items from list 2
// assume list2 has elements of type MyClass where getStr gets the
// string that might appear in list1
Set<String> unavailableItems = list2.stream()
    .map(MyClass::getStr)
    .collect(Collectors.toSet());

// stream the list and use the set to filter it
List<String> unavailable = list1.stream()
            .filter(e -> unavailableItems.contains(e))
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


DSc*_*idt 7

使用流进行操作非常简单易读:

Predicate<String> notIn2 = s -> ! list2.stream().anyMatch(mc -> s.equals(mc.str));
List<String> list3 = list1.stream().filter(notIn2).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


Aru*_*hot 5

终于我有了实现以下方法的方法-

List<String> unavailable = list1.stream()
                .filter(e -> (list2.stream()
                        .filter(d -> d.getStr().equals(e))
                        .count())<1)
                        .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但这也按预期工作。请让我知道这有效吗?如果有人有其他方法可以做同样的事情?


小智 5

list1 = list1.stream().filter(str1-> 
        list2.stream().map(x->x.getStr()).collect(Collectors.toSet())
        .contains(str1)).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

这可能会更有效率。