作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
让我们考虑两个数组列表。
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(3);
list2.add(4);
list2.add(5);
我想在这些列表之间执行 AND 和 OR 运算。例如,在这里,当我执行黑白 list1 和 list2 的 AND 运算时,输出应该是一个仅包含 3 的列表当我执行黑白 list1 和 list2 的 OR 运算时,输出应该是包含 1,2,3,4,5 的列表(而不是 3 重复两次)。
Java有没有可能实现这个场景?在这种情况下我们可以使用 Java 8 Streams 吗?请给我最有效的方式来获得答案。
最佳答案
使用 Stream API:
List<Integer> union = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
List<Integer> intersection = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
<小时/>
没有 Stream API:
List<Integer> intersection = new ArrayList<>(list1);
intersection.retainAll(list2);
List<Integer> union = new ArrayList<>(list1);
List<Integer> toAdd = new ArrayList<>(list2);
toAdd.removeAll(list1); // avoid duplicates
union.addAll(toAdd);
关于java - Java 中列表的 AND/OR 运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29297548/
我是一名优秀的程序员,十分优秀!