Skip to content
Advertisement

How to i iterate and compare two lists

List 1 = [a, b, c, d, 1, e, 1, , 2]
List 2 = [a, b, f, d, 1, e, 1, g, 2]
o/p list = [, , f, , , , , g, ]

Here I’m trying to compare two lists position wise that is the first element from list1 has to be compared with only the first element of list2 and if they are equal it should be replaced with the empty string in the output list and if they are different the element in the second list has to be updated in the output.

Advertisement

Answer

It seems the input lists should have the same length, therefore it is possible to iterate both lists using index, compare the elements at the same index, and put the necessary into the result.

  1. Using for loop
List<String> result = new ArrayList<>();
for (int i = 0, n = list1.size(); i < n; i++) {
    result.add(Objects.equals(list1.get(i), list2.get(i)) ? "" : list2.get(i));
}
  1. Using Stream API (IntStream)
List<String> result = IntStream.range(0, list1.size())
        .mapToObj(i -> Objects.equals(list1.get(i), list2.get(i)) ? "" : list2.get(i))
        .collect(Collectors.toList());
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement