1

There are 2 lists of objects A and B. So List<A> and List<B>. A and B have a common Sting field id which connects them. B also has a numeric field value. We want to sort list A based on the value present in list B.

What's the best way to do it using Java APIs, perhaps like Comparator?

1 Answer 1

5

I would create a map ranking id by value for efficient lookup:

Map<String, Integer> rank = listB.stream()
        .collect(Collectors.toMap(b -> b.id, b -> b.value));

Then you can construct a comparator based on your map and use it to sort the A list:

listA.sort(Comparator.comparing(a -> rank.get(a.id));
Sign up to request clarification or add additional context in comments.

Comments

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.