0

Is it possible to do without external foreach to iterate b. Need to identify common values in 2 arays using Java 8

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
user3428736
  • 864
  • 2
  • 13
  • 33
  • See also http://stackoverflow.com/questions/17863319/java-find-intersection-of-two-arrays – Tunaki Sep 22 '16 at 15:17
  • 1
    `a1 -> (a1.compareTo(b1) ==0)` is quite an obfuscated way to say `a1 -> a1.equals(b1)`. You can, by the way also use `Predicate.isEqual(b1)` or, if you can be sure that there won’t be `null` in your arrays, `b1::equals`. – Holger Sep 22 '16 at 16:32
  • 1
    @Tunaki: these are very poor references. In both cases, the accepted answer doesn’t actually match the question. – Holger Sep 22 '16 at 16:40

2 Answers2

2

I would suggest using sets if you only want the common values (i.e. not taking duplicates into account)

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);
Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
0

Maybe something like this:

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);
}
  • we merge two array into one stream
  • groupBy is counting by value
  • then we filter lists longer than 1, that lists contains duplicates
  • map to key to extract value of duplicated entry
  • print it.

edit: added distinct to initial streams.

Koziołek
  • 2,791
  • 1
  • 28
  • 48