Home > Back-end >  Checking common element between two similar Lists using Streams
Checking common element between two similar Lists using Streams

Time:05-06

Let's say, I've 2 similar lists (not same though). For Example: One List of Integers and another List of Hex String (which can be mapped to Integer), how can I find if there's any common element at same index in both the lists using streams?

Let's consider the following code:

List<Integer> l1 = List.of(11, 12, 13, 14, 15);
List<String> l2 = List.of("F", "E", "D", "C", "B")

boolean isCommon = checkIfCommonElementExists(l1, l2);
System.out.print("There's at least one common element at same index: "   isCommon);

In this example, the 3rd element of both the lists are same i.e 13 or OxD

How can I check (or find) if there's any such common element at same index and break at first match (something like anyMatch()) using Streams? This is a simple problem to solve without streams, but can it be solved using Streams?

CodePudding user response:

You could do something like below to check if any common elements exist

private static boolean checkIfCommonElementExists(List<Integer> list1, List<String> list2) {
    return IntStream.range(0, Math.min(list1.size(), list2.size()))
            .anyMatch(i -> list1.get(i).equals(Integer.parseInt(list2.get(i),16)));
}

or something like below to get the indices of common elemnts

private static int[] findCommonElementIndexes(List<Integer> list1, List<String> list2) {
    return IntStream.range(0, Math.min(list1.size(), list2.size()))
            .filter(i -> list1.get(i).equals(Integer.parseInt(list2.get(i),16)))
            .toArray();
}

for the given example:

List<Integer> l1 = List.of(11, 12, 13, 14, 15);
List<String> l2 = List.of("F", "E", "D", "C", "B");

boolean isCommon = checkIfCommonElementExists(l1, l2);
System.out.println("There's at least one common element at same index: "   isCommon);

System.out.println("Common indices"   Arrays.toString(findCommonElementIndexes(l1,l2)));

output:

There's at least one common element at same index: true
Common indices: [2]
  • Related