使用 java 8 迭代和过滤两个列表 [英] iterating and filtering two lists using java 8
本文介绍了使用 java 8 迭代和过滤两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想迭代两个列表并获得新的过滤列表,该列表的值不会出现在第二个列表中.有人可以帮忙吗?
I want to iterate two lists and get new filtered list which will have values not present in second list. Can anyone help?
我有两个列表 - 一个是字符串列表,另一个是 MyClass
对象列表.
I have two lists - one is list of strings, and the other is list of MyClass
objects.
List<String> list1;
List<MyClass> list2;
MyClass {
MyClass(String val)
{
this.str = val;
}
String str;
...
...
}
我想要基于过滤的字符串列表 -> 检查其值不存在于 list1
中的元素 (abc) 的第二个列表.
I want filtered list of strings based on -> check second list for elements (abc) whose values not present in 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);
现在我想要新的过滤列表 -> 它将具有值 => "lmn".即元素在 list1
中的 list2
中不存在的值.
Now I want new filtered list -> which will have value => "lmn". i.e. values not present in list2
whose elements are in list1
.
推荐答案
这可以使用下面的方法来实现...
this can be achieved using below...
List<String> unavailable = list1.stream()
.filter(e -> !list2.contains(e))
.collect(Collectors.toList());
这篇关于使用 java 8 迭代和过滤两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文