Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I sort two lists of different objects based on the int values in the objects of the second list?

I’m making a network call that gives me a list of CoinPriceQueryResult objects:

public class CoinPriceQueryResult {
    private String coinQueryId;
    private double price;
}

How can I sort this list into the order of my second list of objects:

public class CoinStatus {
    private String coinQueryId;
    private int position;
}

based on the position.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List<CoinQueryResult> listQueryResult = new ArrayList();
listQueryResult.add("penny", 1.15);
listQueryResult.add("nickel", 5.05);
listQueryResult.add("dime", 10.10);

List<CoinStatus> listCoinStatus = new ArrayList();
listCoinStatus.add("nickel", 0);
listCoinStatus.add("penny", 1);
listCoinStatus.add("dime", 2);

I want listQueryResult to be sorted in the order of

nickel, penny, dime

How do I get the sorted list using the int value positionin the CoinStatus object?

>Solution :

First, create a Map that maps each coin name to its position/priority. Then, use Comparator.comparing to sort based on that Map.

Map<String, Integer> position = listCoinStatus.stream().collect(
                Collectors.toMap(CoinStatus::getCoinQueryId, CoinStatus::getPosition));
listQueryResult.sort(Comparator.comparing(r -> position.get(r.getCoinQueryId())));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading