Java 8: Sort or find maximum, minimum entries in maps

May 5, 2014 by Michael

This is cool:

Map.Entry#comparingByKey and Map.Entry#comparingByValue. They both take another comparator or lambda that is used as a delegate for creating a Map.Entry comparator, that can be used to sort maps or find maximum and minimum pairs in a map by key or value like in the following example:

import java.time.LocalDate;
import java.util.Map;
import java.util.Random;
 
import java.util.TreeMap;
 
public class FindMaxMinInMaps {
    public static void main(String...a) {
	final Map<LocalDate, Integer> foobar = new TreeMap<>();
 
	// Fill a date -> int map with 12 random ints between 0 and 100, 
	new Random(System.currentTimeMillis()).ints(0,100).limit(12).forEach(value -> 
		foobar.put(
			LocalDate.now().withMonth(foobar.size() + 1), 
			value
		));
	// print them for verbosity
	foobar.entrySet().forEach(System.out::println);
	// get the maximum
	Map.Entry<LocalDate, Integer> max 
		= foobar
		    // from all entries
		    .entrySet()
		    // stream them
		    .stream()
		    // max, obviously
		    .max(
			    // this one is cool. It generates
			    // Map.Entry comparators by delegating to another
			    // comparator, exists also for keys
			    Map.Entry.comparingByValue(Integer::compareTo)
		    )
		    // Get the optional (optional because the map can be empty)
		    .get();
	System.out.println("Max is " + max);
    }
}

2 comments

  1. Amir Razmjou wrote:

    Saved my day
    Thanks

    Posted on November 22, 2015 at 6:24 AM | Permalink
  2. Subhobroto Roy wrote:

    want to explore more in Java8

    Posted on June 28, 2017 at 1:26 PM | Permalink
Post a Comment

Your email is never published. We need your name and email address only for verifying a legitimate comment. For more information, a copy of your saved data or a request to delete any data under this address, please send a short notice to michael@simons.ac from the address you used to comment on this entry.
By entering and submitting a comment, wether with or without name or email address, you'll agree that all data you have entered including your IP address will be checked and stored for a limited time by Automattic Inc., 60 29th Street #343, San Francisco, CA 94110-4929, USA. only for the purpose of avoiding spam. You can deny further storage of your data by sending an email to support@wordpress.com, with subject “Deletion of Data stored by Akismet”.
Required fields are marked *