Sonali
Sonali

Reputation: 525

Comparing elements at same position of two list using Java 8 stream

I have two lists I want to compare each element of list 1 to list 2 and get result in list 3 e.g

List1 = {99,22,33}

list2 = {11,24,33}

Result:

list3 = {1,-1,0}

How I can do this preferably using stream?

Upvotes: 0

Views: 1515

Answers (1)

WJS
WJS

Reputation: 40034

Try it like this:

This replaces the stream of ints used to index each list, with the result of the comparison. Then collect those into a list.

Note: I added a safeguard to account for different size lists. It will use the smaller of the two to prevent an exception being thrown. But trailing elements of the longer list will be ignored.

List<Integer> list1 = List.of(99, 22, 33);
List<Integer> list2 = List.of(11, 24, 33);

// safeguard against different sized lists.
int minLen = Math.min(list1.size(), list2.size());
List<Integer> result = IntStream.range(0, minLen)
        .map(i -> list1.get(i).compareTo(list2.get(i)))
        .boxed().collect(Collectors.toList());

System.out.println(result);

Prints

[1, -1, 0]

Upvotes: 5

Related Questions