Sort map by value

Setup

Map<Integer, String> CANDY_BARS;

@Before
public void setUp () {
    
    CANDY_BARS = new HashMap<Integer, String>();
    CANDY_BARS.put(233, "REESE'S P-BUTTER CUPS");
    CANDY_BARS.put(222, "REESE'S P-BUTTER CUPS");
    CANDY_BARS.put(284, "TWIX, CARAMEL");
    CANDY_BARS.put(232, "ALMOND JOY");
    CANDY_BARS.put(149, "YORK PEPPERMINT PATTIE");
}

Straight up Java

@Test
public void sort_map_by_values_java () {
    
    Comparator<Map.Entry<Integer, String>> byMapValues = new Comparator<Map.Entry<Integer, String>>() {
        @Override
        public int compare(Map.Entry<Integer, String> left, Map.Entry<Integer, String> right) {
            return left.getValue().compareTo(right.getValue());
        }
    };
    
    // create a list of map entries
    List<Map.Entry<Integer, String>> candyBars = new ArrayList<Map.Entry<Integer, String>>();
    
    // add all candy bars
    candyBars.addAll(CANDY_BARS.entrySet());
    
    // sort the collection
    Collections.sort(candyBars, byMapValues);
    
    logger.info(candyBars);
    
    assertEquals("ALMOND JOY", candyBars.get(0).getValue());
}

Java 8

@Test
public void sort_map_by_values_java8() {

    Comparator<Entry<Integer, String>> byValue = (entry1, entry2) -> entry1.getValue().compareTo(
            entry2.getValue());
    
    Optional<Entry<Integer, String>> val = CANDY_BARS
            .entrySet()
            .stream()
            .sorted(byValue.reversed())
            .findFirst();
    
    logger.info(val);
    
    assertEquals("YORK PEPPERMINT PATTIE", val.get().getValue());
}

FROM HERE

And some good discussion here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s