java 8 中的减法运算用于减去列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30977759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:55:05 来源:igfitidea点击:
Minus operation in java 8 for subtracting Lists
提问by Manu Joy
Suppose I have two lists:
假设我有两个列表:
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2, 4, 5);
Now I want to perform (list1 - list2)
. The expected ouptut is {3}
. How to do this using java 8 streams?
现在我想表演(list1 - list2)
。预期的输出是{3}
。如何使用 java 8 流来做到这一点?
回答by Eran
If you must use Streams :
如果您必须使用 Streams :
List<Integer> diff = list1.stream()
.filter(i -> !list2.contains(i))
.collect (Collectors.toList());
回答by Hiren
Try this:
试试这个:
List<Integer> difference = new ArrayList<>(list1);
difference.removeAll(list2);
System.out.println("Remove: " + difference); //3
回答by Igal
Using Apache commons:
使用 Apache 公共资源:
CollectionUtils.subtract(list1, list2);
Pros: Very readable. Cons: No type safety
优点:可读性很强。缺点:没有类型安全