使用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".即list2
中不存在其元素在list1
中的值.
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屋!
查看全文