Home > Blockchain >  How do I sort two lists of different objects based on the int values in the objects of the second li
How do I sort two lists of different objects based on the int values in the objects of the second li

Time:02-05

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.

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?

CodePudding user response:

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())));
  •  Tags:  
  • java
  • Related