是否可以在没有外部foreach的情况下迭代b。需要使用Java 8
识别2个arays中的常见值Integer a[]={1,2,3,4};
Integer b[]={9,8,2,3};
for(Integer b1:b) {
Stream.of(a).filter(a1 -> (a1.compareTo(b1) ==0)).forEach(System.out::println);
}
Output: 2 3
答案 0 :(得分:1)
如果您只想要公共值(即不考虑重复项),我建议使用集合
Integer a[]={1,2,3,4};
Integer b[]={9,8,2,3};
Set<Integer> aSet = new HashSet<>(Arrays.asList(a));
Set<Integer> bSet = new HashSet<>(Arrays.asList(b));
aSet.retainAll(bSet);
答案 1 :(得分:0)
也许是这样的:
public static void main(String[] args) {
Integer a[] = {1, 2, 3, 4};
Integer b[] = {9, 8, 2, 3};
Stream<Integer> as = Arrays.stream(a).distinct();
Stream<Integer> bs = Arrays.stream(b).distinct();
List<Integer> collect = Stream.concat(as, bs)
.collect(Collectors.groupingBy(Function.identity()))
.entrySet()
.stream()
.filter(e -> e.getValue().size() > 1)
.map(e -> e.getKey())
.collect(Collectors.toList());
System.out.println(collect);
}
groupBy
按值计算map
键以提取重复条目的值编辑:为初始流添加了不同的内容。