0

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?

1
  • 1
    Are lists guaranteed to have same size? If not how would you like such situation to be handled? Commented Apr 4, 2020 at 21:19

1 Answer 1

5

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]
Sign up to request clarification or add additional context in comments.

5 Comments

Nice solution but as @Pshemo said, it will work only when both list will have the same size. If list2 will have less members, a runtime exception will be thrown. Anyway, OP mentioned Java 8, so List.of are part of the Java 9, therefore I'd change it to Arrays.asList :)
Yeah. I amended my answer and used Math.min() to get the minimum length to avoid an exception. It is up to the OP if they want it or not.
Yes both list will be of same size. Thanks for solution this will work for me @WJS
or use mapToObj instead of the map...boxed combination
@WJS It is indeed strange. A recent survey collected feedback and similar comments were marked by me over it. I believe the site somehow lacks to refrain the "rich from becoming richer". (no further discussion here about it though)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.