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

Sonali :

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?

WJS :

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]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409835&siteId=1