Home » Core Java » Collectors to Map in Java

About Frank Yee

Frank holds a Bachelor of Science in Biology from The City University of New York (The City College of New York) and a Bachelor of Arts in Computer Science from The City University of New York (Hunter College). As an undergraduate, he had taken courses where programs were written in Fortran, Basic, Pascal, COBOL, and Assembly Language for the IBM 4341 Mainframe. He has been a software developer for over 30 years having built desktop apps, mobile apps and web apps. He has built software in C/C++, VisualBasic, TCL, Java, PHP, XML/XSLT, Perl, Shell Scripting and Python. Frank was also an educator in The City University of New York (Borough of Manhattan Community College, New York City College of Technology) having taught courses in Pascal, VisualBasic, C++ for over 10 years. Finally, he has recently helped students create programs in Lisp, R, Masm, Haskell, Scheme and Prolog.

Collectors to Map in Java

1. Introduction

The Collectors class is in the java.util.stream package. The Collectors class contains static methods which return a Collector to allow for various reduction operations. This article will discuss the toMap and the toConcurrentMap methods. These methods will return a Map or a ConcurrentMap. In addition, we will also be discussing the SortedMap interface. Finally, we conclude this article with a code sample and the corresponding output.

2. Some definitions for Collectors to Map

  • A method is a term for function when discussed in Object Oriented Programming. As such it may have input parameters, return a type, and may be invoked or called.
  • A static method is a class-level method that does not require object instantiation for the method to be invoked.
  • An instance method is a method that does require object instantiation for the method to be invoked.
  • An interface allows for an implementing class to fill in the code for the method signatures declared.
  • Overloaded methods are methods defined in a class which share the same name and return type but have different number or types of parameters.
  • A subclass can be created from a superclass or base class by extending the superclass and overriding methods found in the superclass or adding additional methods not found in the superclass.
  • The base class for all classes in Java is the Object class found in the java.lang package.
  • Abstract classes cannot be instantiated. A subclass must implement the abstract methods declared in the abstract class.
  • Polymorphism as discussed in the context of Object Oriented Programming involves the use of all of the above.

3. Map, ConcurrentMap, and SortedMap interfaces

ConcurrentMap and SortedMap interfaces extend the Map interface. The ConcurrentMap interface allows for thread safety while the SortedMap interface allows for the ordering of Map keys.

3.1 The following classes implement the Map Interface:

  • AbstractMap (abstract Class)
  • Attributes
  • AuthProvider (abstract class)
  • ConcurrentHashMap
  • ConcurrentSkipListMap
  • EnumMap
  • HashMap
  • Hashtable
  • IdentityHashMap
  • LinkedHashMap
  • PrinterStateReasons (final class)
  • Properties
  • Provider (abstract class)
  • RenderingHints
  • SimpleBindings
  • TabularDataSupport
  • TreeMap
  • UIDefaults
  • WeakHashMap

3.2 The following classes implement the ConcurrentMap interface:

  • ConcurrentHashMap
  • ConcurrentSkipListMap

3.3 The following classes implement the SortedMap interface

  • ConcurrentSkipListMap
  • TreeMap

4. The collectors to Map and toConcurrentMap methods

For both toMap and toConcurrentMap methods, there are 3 overloaded methods.

The default Map returned from toMap methods would be HashMap while the default Map returned from toConcurrentMap methods would be ConcurrentHashMap.

keyMappera function that provides the keys for the resulting Map
valueMappera function that provides the values for the resulting Map
mergeFunctiona function that resolves conflicts arising from duplicate keys
mapSupplierdetermines which would be the returned Map object
Parameter descriptions
Method
Parameters
TypeName
toMap
FunctionkeyMapper
FunctionvalueMapper
toMap
FunctionkeyMapper
FunctionvalueMapper
BinaryOperatormergeFunction
toMap
FunctionkeyMapper
FunctionvalueMapper
BinaryOperatormergeFunction
SuppliermapSupplier
toConcurrentMap
FunctionkeyMapper
FunctionvalueMapper
toConcurrentMap
FunctionkeyMapper
FunctionvalueMapper
BinaryOperatormergeFunction
toConcurrentMap
FunctionkeyMapper
FunctionvalueMapper
BinaryOperatormergeFunction
SuppliermapSupplier

5. Example

Disclaimer: The data used in the following example is computer-generated and does not represent real data of real people.

The following example streams a list of transactions that contains the account number, name, phone numbers, and dollars spent and creates a map from it.

A particular account number is associated with a person. That person may have multiple phone numbers which were used for purchases. The purpose of the application is to output a list of the individuals with only one primary phone number with which to contact the person. The choice for the phone number is the number with which the greatest total purchases were made. In the rare event in which the total purchases for different phone numbers for a person are the same, there is a priority for the different area codes of the phone used.

5.1 Sample Code

Click to see the output.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ProcessTransactions {
	
	public static String methodName() {
		return new Exception().getStackTrace()[1].getMethodName();
	}
	public static List<Transaction> getTransactionListWithNoDups(List<Transaction>transactions) {
		ArrayList<Transaction>newList = new ArrayList<Transaction>();

		for (Transaction transaction: transactions) {
			boolean gotMatch = false;
			for (Transaction listTransaction: newList) {
				if (listTransaction.equals(transaction)) {
					gotMatch = true;
					break;
				}
			}
			if (!gotMatch) {
				newList.add(transaction);
			}
		}
		return newList;
	}

	public static List<Transaction> createTransactions() {
		String [][] data = {
				{    "Julie", "Barrister", "21144", "(917) 555-3287",  "8205.09"},
				{    "Julie", "Barrister", "21144", "(917) 555-1675",  "1744.65"},
				{    "Julie", "Barrister", "21144", "(646) 555-7644",   "274.67"},
				{    "Julie", "Barrister", "21144", "(631) 555-6938",  "3309.86"},
				{    "Julie", "Barrister", "21144", "(718) 555-2965",   "783.60"},
				{ "Michelle", "Albertson", "45581", "(917) 555-1363",   "721.76"},
				{ "Michelle", "Albertson", "45581", "(917) 555-6071",  "1272.34"},
				{ "Michelle", "Albertson", "45581", "(518) 555-4079",  "1272.34"},
				{ "Michelle", "Albertson", "45581", "(212) 555-5955",  "1272.34"},
				{ "Michelle", "Albertson", "45581", "(917) 555-4045",  "1056.65"},
				{ "Michelle", "Albertson", "45581", "(917) 555-0107",   "185.05"},
				{     "John",   "Tillson", "22839", "(646) 555-4314",  "5752.88"},
				{     "John",   "Tillson", "22839", "(917) 555-4602",   "321.18"},
				{     "John",   "Tillson", "22839", "(212) 555-8018",   "669.74"},
				{     "John",   "Tillson", "22839", "(718) 555-8923",  "6116.53"},
				{   "Warren",       "Lee", "94328", "(718) 555-4652",  "1141.72"},
				{   "Warren",       "Lee", "94328", "(212) 555-5515",  "1289.81"},
				{   "Warren",       "Lee", "94328", "(718) 555-7599",    "66.12"},
				{   "Warren",       "Lee", "94328", "(631) 555-8512",  "2846.22"},
				{   "Warren",       "Lee", "94328", "(212) 555-9497",  "3847.88"},
				{   "Warren",       "Lee", "94328", "(212) 555-9357",   "341.63"},
				{    "Zenia",    "Lasher", "63937", "(516) 555-8570",   "115.11"},
				{    "Zenia",    "Lasher", "63937", "(646) 555-9940",   "811.40"},
				{    "Zenia",    "Lasher", "63937", "(212) 555-5194",   "482.39"},
				{    "Zenia",    "Lasher", "63937", "(917) 555-1854",  "1551.28"},
				{    "Kevin",   "Mickens", "77205", "(718) 555-4650",  "1991.75"},
				{    "Kevin",   "Mickens", "77205", "(212) 555-9212",  "2128.45"},
				{    "Kevin",   "Mickens", "77205", "(518) 555-1061",  "2943.39"},
				{   "Yvonne",  "Quantico", "83341", "(516) 555-6968",  "2856.09"},
				{   "Yvonne",  "Quantico", "83341", "(631) 555-7763",   "713.36"},
				{   "Yvonne",  "Quantico", "83341", "(631) 555-5896",   "880.25"},
				{   "Yvonne",  "Quantico", "83341", "(631) 555-1493",   "750.15"},
				{   "Yvonne",  "Quantico", "83341", "(518) 555-3394",  "3563.78"},
				{   "Oliver",   "Roberts", "66822", "(516) 555-6366",  "5792.25"},
				{   "Oliver",   "Roberts", "66822", "(631) 555-4212",   "559.85"},
				{   "Oliver",   "Roberts", "66822", "(631) 555-9948",   "307.82"},
				{   "Oliver",   "Roberts", "66822", "(631) 555-6474",   "102.38"},
				{   "Oliver",   "Roberts", "66822", "(646) 555-3666",  "2253.37"},
				{ "Victoria",   "Tillson", "85361", "(516) 555-7517",   "947.92"},
				{ "Victoria",   "Tillson", "85361", "(631) 555-8346",  "2857.27"},
				{ "Victoria",   "Tillson", "85361", "(631) 555-2377",   "632.28"},
				{    "Paula",  "Harrison", "26262", "(518) 555-4495",  "4280.57"},
				{    "Paula",  "Harrison", "26262", "(212) 555-5639",  "7794.50"},
				{    "Paula",  "Harrison", "26262", "(516) 555-8609",  "5178.87"},
				{    "Paula",  "Harrison", "26262", "(631) 555-8516",  "2086.11"},
				{    "Freda", "Stapleton", "72652", "(212) 555-0800",  "4665.87"},
				{    "Freda", "Stapleton", "72652", "(631) 555-6978",   "574.62"},
				{    "Freda", "Stapleton", "72652", "(718) 555-2429",  "1322.35"},
				{    "Queen",   "Tillson", "67169", "(646) 555-0590",   "665.89"},
				{    "Queen",   "Tillson", "67169", "(516) 555-7907",   "315.66"},
				{    "Queen",   "Tillson", "67169", "(516) 555-6804",  "7217.85"},
				{    "Queen",   "Tillson", "67169", "(718) 555-8152",   "778.31"},
				{    "Queen",   "Tillson", "67169", "(212) 555-5951",  "1181.02"},
				{    "Queen",   "Tillson", "67169", "(917) 555-0052",  "1012.82"},
				{    "Laura",     "Gavin", "77790", "(516) 555-0615",  "2155.50"},
				{    "Laura",     "Gavin", "77790", "(646) 555-4320",    "87.39"},
				{    "Laura",     "Gavin", "77790", "(518) 555-4944",   "628.97"},
				{    "Laura",     "Gavin", "77790", "(646) 555-8332",   "826.65"},
				{    "Julie",    "Harris", "32221", "(631) 555-4728",  "3387.69"},
				{    "Julie",    "Harris", "32221", "(646) 555-3643", "38776.50"},
				{    "Julie",    "Harris", "32221", "(917) 555-3847",   "419.75"},
				{    "Julie",    "Harris", "32221", "(631) 555-4924",   "788.83"},
				{    "Julie",    "Harris", "32221", "(212) 555-6936",    "15.25"},
				{ "Michelle",  "Harrison", "44460", "(212) 555-5522",   "497.93"},
				{ "Michelle",  "Harrison", "44460", "(212) 555-3738",   "352.73"},
				{ "Michelle",  "Harrison", "44460", "(212) 555-1351",   "983.13"},
				{ "Michelle",  "Harrison", "44460", "(917) 555-8179",   "108.81"},
				{    "Garry",       "Lee", "31471", "(516) 555-7130",  "1573.11"},
				{    "Garry",       "Lee", "31471", "(212) 555-5324",   "619.44"},
				{    "Garry",       "Lee", "31471", "(631) 555-2783",  "2089.00"},
				{    "Garry",       "Lee", "31471", "(212) 555-4763",   "622.21"},
				{    "Garry",       "Lee", "31471", "(516) 555-1300",  "1071.09"},
				{      "Ida",     "Olden", "86092", "(518) 555-2803",  "2690.21"},
				{      "Ida",     "Olden", "86092", "(917) 555-2207",   "512.03"},
				{      "Ida",     "Olden", "86092", "(631) 555-0085",   "631.42"},
				{      "Ida",     "Olden", "86092", "(518) 555-9402",   "688.26"},
				{    "Donna",    "Dallas", "57010", "(718) 555-0330", "43928.50"},
				{    "Donna",    "Dallas", "57010", "(631) 555-0852",  "1623.95"},
				{    "Donna",    "Dallas", "57010", "(718) 555-9695",  "1244.96"},
				{    "Donna",    "Dallas", "57010", "(646) 555-3638",   "729.54"},
				{   "Victor", "Barrister", "93245", "(631) 555-0304",   "949.33"},
				{   "Victor", "Barrister", "93245", "(516) 555-7210",  "3575.09"},
				{   "Victor", "Barrister", "93245", "(212) 555-7660",  "5264.27"},
				{   "Victor", "Barrister", "93245", "(212) 555-0380",  "2388.30"},
				{   "Calvin", "Ellsworth", "48508", "(516) 555-6529",   "288.45"},
				{   "Calvin", "Ellsworth", "48508", "(646) 555-1321",   "787.00"},
				{   "Calvin", "Ellsworth", "48508", "(917) 555-8595",   "948.15"},
				{   "Calvin", "Ellsworth", "48508", "(917) 555-4224",  "3212.30"},
				{   "Calvin", "Ellsworth", "48508", "(518) 555-3741",  "1036.52"},
				{   "Calvin", "Ellsworth", "48508", "(516) 555-1910",  "1848.41"},
				{    "Kevin", "Stapleton", "45565", "(516) 555-0930",  "3224.65"},
				{    "Kevin", "Stapleton", "45565", "(516) 555-2136",   "885.96"},
				{    "Kevin", "Stapleton", "45565", "(646) 555-2048", "10510.67"},
				{    "Kevin", "Stapleton", "45565", "(718) 555-9657",   "580.86"},
				{   "Joseph", "Kendricks", "62068", "(518) 555-0249",  "1026.78"},
				{   "Joseph", "Kendricks", "62068", "(212) 555-7486",   "150.52"},
				{   "Joseph", "Kendricks", "62068", "(516) 555-7813",   "444.96"},
				{   "Joseph", "Kendricks", "62068", "(631) 555-4661",  "1098.24"},
				{   "Joseph", "Kendricks", "62068", "(518) 555-0167",    "95.97"},
				{   "Joseph", "Kendricks", "62068", "(212) 555-8809",   "677.55"},
				{    "Garry",   "Paulson", "86036", "(917) 555-4386",     "6.94"},
				{    "Garry",   "Paulson", "86036", "(917) 555-7134",  "3835.47"},
				{    "Garry",   "Paulson", "86036", "(718) 555-0187",   "350.00"},
				{    "Garry",   "Paulson", "86036", "(212) 555-3707",  "2019.02"},
		};

		List<Transaction>transactions = new ArrayList<Transaction>();

		for (String [] row: data) {
			transactions.add(new Transaction(new Customer(row[0], row[1], row[2]), row[3], Double.parseDouble(row[4])));
		}
		return transactions;
	}
	static public Map<String, Object> listWithUniqueKeysToMap(List<Transaction> transactions) {
		Map<String, Object> result = new HashMap<String, Object>(); 

		result.put("methodDescription", String.format("Executing %s with toMap(keyMapper, valueMapper)\n", methodName()));

		result.put("result", transactions.stream().collect(Collectors.toMap(Transaction::getAccountNumber, Function.identity())));

		return result;
	}

	static public Map<String, Object> listToMap(List<Transaction> transactions) {
		Map<String, Object> result = new HashMap<String, Object>(); 

		result.put("methodDescription", String.format("Executing %s with toMap(keyMapper, valueMapper, mergeFunction)\n", methodName()));

		result.put("result", transactions.stream().collect(Collectors.toMap(Transaction::getAccountNumber, Function.identity(), (existing, replacement) -> existing)));

		return result;
	}

	static public Map<String, Object> listToWeakHashMap(List<Transaction> transactions) {
		Map<String, Object> result = new HashMap<String, Object>(); 

		result.put("methodDescription", String.format("Executing %s with toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)\n", methodName()));
		
		result.put("result", transactions.stream().collect(Collectors.toMap(Transaction::getAccountNumber, Function.identity(), (existing, replacement) -> existing, WeakHashMap::new)));

		return result;
	}

	static public Map<String, Object> listToSortedMap(List<Transaction> transactions) {
		Map<String, Object> result = new HashMap<String, Object>(); 

		BinaryOperator<Transaction> breakSame = (v1, v2) -> v1.getTotalPurchases() > v2.getTotalPurchases() ? v1: v2;

		result.put("methodDescription", String.format("Executing %s with toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)\n", methodName()));
		
	    result.put("result", transactions.stream().collect(Collectors.toMap(Transaction::getAccountNumber, Function.identity(),
	    		breakSame, TreeMap::new)));
	    
	    return result;

	}

	static public Map<String, Object> listToSortedConcurrentMap(List<Transaction> transactions) {
		Map<String, Object> result = new HashMap<String, Object>(); 

		BinaryOperator<Transaction> breakSame = (v1, v2) -> v1.getTotalPurchases() > v2.getTotalPurchases() ? v1: v2;

		result.put("methodDescription", String.format("Executing %s with toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)\n", methodName()));
		
	    result.put("result", transactions.stream().collect(Collectors.toConcurrentMap(Transaction::getAccountNumber, Function.identity(),
	    		breakSame, ConcurrentSkipListMap::new)));
	    
	    return result;

	}

	static public Map<String, Object> listWithUniqueKeysToConcurrentMap(List<Transaction> transactions) {
		Map<String, Object> result = new HashMap<String, Object>(); 

		result.put("methodDescription", String.format("Executing %s with toConcurrentMap(keyMapper, valueMapper)\n", methodName()));
		
		result.put("result", transactions.stream().collect(Collectors.toConcurrentMap(Transaction::getAccountNumber, Function.identity())));

	    return result;
		
	}

	static public Map<String, Object> listToConcurrentMap(List<Transaction> transactions) {
		Map<String, Object> result = new HashMap<String, Object>(); 

		BinaryOperator<Transaction> breakSame = (v1, v2) -> v1.getTotalPurchases() > v2.getTotalPurchases() ? v1: v2;

		result.put("methodDescription", String.format("Executing %s with toConcurrentMap(keyMapper, valueMapper, mergeFunction, mapSupplier)\n", methodName()));
		
	    result.put("result", transactions.stream().collect(Collectors.toConcurrentMap(Transaction::getAccountNumber, Function.identity(),
	    		breakSame, ConcurrentSkipListMap::new)));
	    		
	    return result;

	}
	static public Map<String, Object> listToConcurrentMap(List<Transaction> transactions, BinaryOperator<Transaction> breakSame) {
		Map<String, Object> result = new HashMap<String, Object>(); 
				
		result.put("methodDescription", String.format("Executing %s with toConcurrentMap(keyMapper, valueMapper, mergeFunction)\n", methodName()));

		result.put("result", transactions.stream().collect(Collectors.toConcurrentMap(Transaction::getAccountNumber, Function.identity(),
						breakSame)));

		return result;

	}
	public static void printBanner(String type, String methodDescription) {
		int bannerLength = 110;
		StringBuffer stars = new StringBuffer();
		StringBuffer dashes = new StringBuffer();
		String typeformat = "\n%" + String.format("%d", (bannerLength-type.length())/2 + type.length()) + "s\n\n";
		String descformat = "%" + String.format("%d", (bannerLength-methodDescription.length())/2 + methodDescription.length()) + "s\n";
		for (int i = 0; i < bannerLength; i++) stars.append('*'); 
		for (int i = 0; i < bannerLength; i++) dashes.append('-'); 

		System.out.println(stars);
		System.out.printf(typeformat, type);
		System.out.printf(descformat, methodDescription);
		System.out.println(dashes);
		System.out.printf("Account Number      Phone Number     Name                        Total Purchases\n");
		System.out.println(stars + "\n");
	}
	@SuppressWarnings("unchecked")
	public static void printTransactions(Map<String, Object>transactionData) {
		Map<String, Transaction>transactions = (Map<String, Transaction>)transactionData.get("result");
		String methodDescription = (String)transactionData.get("methodDescription");

		BiConsumer<? super String, ? super Transaction>printLine = (key, transaction) -> {

			System.out.printf("%-17s %-18s %-20s %22.2f\n", key, transaction.getPhoneNumber(), transaction.getFirstName() + " " + transaction.getLastName(), transaction.getTotalPurchases());
		};
		
		printBanner(transactions.getClass().getName(), methodDescription);
		transactions.forEach(printLine);
		System.out.println("\n\n");
	}

	public static void main(String[] args)
    {
		List<Transaction> transactions = createTransactions();
		List<Transaction> transactionsListWithUniqueKeys = getTransactionListWithNoDups(transactions);
		ArrayList<Map<String, Object>>transactionMaps = new ArrayList<Map<String, Object>>(); 

		transactionMaps.add(listWithUniqueKeysToMap(transactionsListWithUniqueKeys));
		transactionMaps.add(listToMap(transactions));
		transactionMaps.add(listToWeakHashMap(transactions));
		transactionMaps.add(listToSortedMap(transactions));
		
		transactionMaps.add(listWithUniqueKeysToConcurrentMap(transactionsListWithUniqueKeys));
		transactionMaps.add(listToConcurrentMap(transactions, new ChooseTransaction()));
		BinaryOperator<Transaction> breakSame = (v1, v2) -> v1.getTotalPurchases() > v2.getTotalPurchases() ? v1: v2;
		transactionMaps.add(listToConcurrentMap(transactions, breakSame));
		transactionMaps.add(listToConcurrentMap(transactions));
		transactionMaps.add(listToSortedConcurrentMap(transactions));
		for (Map<String, Object> transactionMap: transactionMaps) {
	    	printTransactions(transactionMap);
		}
    }
}
class Customer {
	String firstName;
	String lastName;
	String accountNumber;
	String phoneNumber;
	double totalPurchases;
	
	public Customer(String firstName, String lastName, String accountNumber) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.accountNumber = accountNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public String getAccountNumber() {
		return accountNumber;
	}
}
class Transaction {
	private Customer customer;
	private String phoneNumber;
	private double totalPurchases;
	
	public Transaction(Customer customer, String phoneNumber, double totalPurchases) {
		this.customer = customer;
		this.phoneNumber = phoneNumber;
		this.totalPurchases = totalPurchases;
	}
	public String getFirstName() {
		return customer.getFirstName();
	}
	public String getLastName() {
		return customer.getLastName();
	}
	public String getAccountNumber() {
		return customer.getAccountNumber();
	}
	public String getPhoneNumber() {
		return phoneNumber;
	}
	public double getTotalPurchases() {
		return totalPurchases;
	}
	public boolean equals(Transaction transaction) {
		boolean rv = false;

		if (this.getAccountNumber().equals(transaction.getAccountNumber()))
			rv = true;

		return rv;
	}
}
class ChooseTransaction implements BinaryOperator<Transaction> {

	public int preferredAreaCode(String phoneNumber) {
		String [] areaCodes = {"516", "631", "212", "646", "718", "917", "518"};
		int rv = -1;
		
		for (int i = 0; i < areaCodes.length; i++) {
			if (phoneNumber.substring(1, 4).equals(areaCodes[i])) {
				rv = i;
			}
		}
		return rv;
	}
	@Override
	public Transaction apply(Transaction transaction1, Transaction transaction2) {
		Transaction rv;
		if (transaction1.getTotalPurchases() > transaction2.getTotalPurchases()) {
			rv = transaction1;
		} else if (transaction1.getTotalPurchases() < transaction2.getTotalPurchases()) {
			rv = transaction2;
		} else if (preferredAreaCode(transaction1.getPhoneNumber()) < preferredAreaCode(transaction2.getPhoneNumber())) {
			rv = transaction1;
		} else
			rv = transaction2;
		return rv;
	}
}

5.2 Sample Output

Click to see the code.

**************************************************************************************************************

                                              java.util.HashMap

                    Executing listWithUniqueKeysToMap with toMap(keyMapper, valueMapper)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

67169             (646) 555-0590     Queen Tillson                        665.89
93245             (631) 555-0304     Victor Barrister                     949.33
86092             (518) 555-2803     Ida Olden                           2690.21
94328             (718) 555-4652     Warren Lee                          1141.72
21144             (917) 555-3287     Julie Barrister                     8205.09
62068             (518) 555-0249     Joseph Kendricks                    1026.78
45565             (516) 555-0930     Kevin Stapleton                     3224.65
72652             (212) 555-0800     Freda Stapleton                     4665.87
22839             (646) 555-4314     John Tillson                        5752.88
57010             (718) 555-0330     Donna Dallas                       43928.50
66822             (516) 555-6366     Oliver Roberts                      5792.25
48508             (516) 555-6529     Calvin Ellsworth                     288.45
77790             (516) 555-0615     Laura Gavin                         2155.50
63937             (516) 555-8570     Zenia Lasher                         115.11
26262             (518) 555-4495     Paula Harrison                      4280.57
32221             (631) 555-4728     Julie Harris                        3387.69
31471             (516) 555-7130     Garry Lee                           1573.11
77205             (718) 555-4650     Kevin Mickens                       1991.75
83341             (516) 555-6968     Yvonne Quantico                     2856.09
45581             (917) 555-1363     Michelle Albertson                   721.76
86036             (917) 555-4386     Garry Paulson                          6.94
44460             (212) 555-5522     Michelle Harrison                    497.93
85361             (516) 555-7517     Victoria Tillson                     947.92



**************************************************************************************************************

                                              java.util.HashMap

                    Executing listToMap with toMap(keyMapper, valueMapper, mergeFunction)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

67169             (646) 555-0590     Queen Tillson                        665.89
93245             (631) 555-0304     Victor Barrister                     949.33
86092             (518) 555-2803     Ida Olden                           2690.21
94328             (718) 555-4652     Warren Lee                          1141.72
21144             (917) 555-3287     Julie Barrister                     8205.09
62068             (518) 555-0249     Joseph Kendricks                    1026.78
45565             (516) 555-0930     Kevin Stapleton                     3224.65
72652             (212) 555-0800     Freda Stapleton                     4665.87
22839             (646) 555-4314     John Tillson                        5752.88
57010             (718) 555-0330     Donna Dallas                       43928.50
66822             (516) 555-6366     Oliver Roberts                      5792.25
48508             (516) 555-6529     Calvin Ellsworth                     288.45
77790             (516) 555-0615     Laura Gavin                         2155.50
63937             (516) 555-8570     Zenia Lasher                         115.11
26262             (518) 555-4495     Paula Harrison                      4280.57
32221             (631) 555-4728     Julie Harris                        3387.69
31471             (516) 555-7130     Garry Lee                           1573.11
77205             (718) 555-4650     Kevin Mickens                       1991.75
83341             (516) 555-6968     Yvonne Quantico                     2856.09
45581             (917) 555-1363     Michelle Albertson                   721.76
86036             (917) 555-4386     Garry Paulson                          6.94
44460             (212) 555-5522     Michelle Harrison                    497.93
85361             (516) 555-7517     Victoria Tillson                     947.92



**************************************************************************************************************

                                            java.util.WeakHashMap

         Executing listToWeakHashMap with toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

45565             (516) 555-0930     Kevin Stapleton                     3224.65
22839             (646) 555-4314     John Tillson                        5752.88
32221             (631) 555-4728     Julie Harris                        3387.69
21144             (917) 555-3287     Julie Barrister                     8205.09
57010             (718) 555-0330     Donna Dallas                       43928.50
72652             (212) 555-0800     Freda Stapleton                     4665.87
26262             (518) 555-4495     Paula Harrison                      4280.57
94328             (718) 555-4652     Warren Lee                          1141.72
44460             (212) 555-5522     Michelle Harrison                    497.93
31471             (516) 555-7130     Garry Lee                           1573.11
62068             (518) 555-0249     Joseph Kendricks                    1026.78
85361             (516) 555-7517     Victoria Tillson                     947.92
86036             (917) 555-4386     Garry Paulson                          6.94
93245             (631) 555-0304     Victor Barrister                     949.33
66822             (516) 555-6366     Oliver Roberts                      5792.25
67169             (646) 555-0590     Queen Tillson                        665.89
86092             (518) 555-2803     Ida Olden                           2690.21
63937             (516) 555-8570     Zenia Lasher                         115.11
77790             (516) 555-0615     Laura Gavin                         2155.50
45581             (917) 555-1363     Michelle Albertson                   721.76
48508             (516) 555-6529     Calvin Ellsworth                     288.45
77205             (718) 555-4650     Kevin Mickens                       1991.75
83341             (516) 555-6968     Yvonne Quantico                     2856.09



**************************************************************************************************************

                                              java.util.TreeMap

          Executing listToSortedMap with toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

21144             (917) 555-3287     Julie Barrister                     8205.09
22839             (718) 555-8923     John Tillson                        6116.53
26262             (212) 555-5639     Paula Harrison                      7794.50
31471             (631) 555-2783     Garry Lee                           2089.00
32221             (646) 555-3643     Julie Harris                       38776.50
44460             (212) 555-1351     Michelle Harrison                    983.13
45565             (646) 555-2048     Kevin Stapleton                    10510.67
45581             (212) 555-5955     Michelle Albertson                  1272.34
48508             (917) 555-4224     Calvin Ellsworth                    3212.30
57010             (718) 555-0330     Donna Dallas                       43928.50
62068             (631) 555-4661     Joseph Kendricks                    1098.24
63937             (917) 555-1854     Zenia Lasher                        1551.28
66822             (516) 555-6366     Oliver Roberts                      5792.25
67169             (516) 555-6804     Queen Tillson                       7217.85
72652             (212) 555-0800     Freda Stapleton                     4665.87
77205             (518) 555-1061     Kevin Mickens                       2943.39
77790             (516) 555-0615     Laura Gavin                         2155.50
83341             (518) 555-3394     Yvonne Quantico                     3563.78
85361             (631) 555-8346     Victoria Tillson                    2857.27
86036             (917) 555-7134     Garry Paulson                       3835.47
86092             (518) 555-2803     Ida Olden                           2690.21
93245             (212) 555-7660     Victor Barrister                    5264.27
94328             (212) 555-9497     Warren Lee                          3847.88



**************************************************************************************************************

                                    java.util.concurrent.ConcurrentHashMap

          Executing listWithUniqueKeysToConcurrentMap with toConcurrentMap(keyMapper, valueMapper)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

67169             (646) 555-0590     Queen Tillson                        665.89
93245             (631) 555-0304     Victor Barrister                     949.33
21144             (917) 555-3287     Julie Barrister                     8205.09
94328             (718) 555-4652     Warren Lee                          1141.72
86092             (518) 555-2803     Ida Olden                           2690.21
22839             (646) 555-4314     John Tillson                        5752.88
72652             (212) 555-0800     Freda Stapleton                     4665.87
45565             (516) 555-0930     Kevin Stapleton                     3224.65
62068             (518) 555-0249     Joseph Kendricks                    1026.78
57010             (718) 555-0330     Donna Dallas                       43928.50
66822             (516) 555-6366     Oliver Roberts                      5792.25
77790             (516) 555-0615     Laura Gavin                         2155.50
48508             (516) 555-6529     Calvin Ellsworth                     288.45
63937             (516) 555-8570     Zenia Lasher                         115.11
26262             (518) 555-4495     Paula Harrison                      4280.57
32221             (631) 555-4728     Julie Harris                        3387.69
31471             (516) 555-7130     Garry Lee                           1573.11
77205             (718) 555-4650     Kevin Mickens                       1991.75
45581             (917) 555-1363     Michelle Albertson                   721.76
83341             (516) 555-6968     Yvonne Quantico                     2856.09
44460             (212) 555-5522     Michelle Harrison                    497.93
86036             (917) 555-4386     Garry Paulson                          6.94
85361             (516) 555-7517     Victoria Tillson                     947.92



**************************************************************************************************************

                                    java.util.concurrent.ConcurrentHashMap

          Executing listToConcurrentMap with toConcurrentMap(keyMapper, valueMapper, mergeFunction)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

67169             (516) 555-6804     Queen Tillson                       7217.85
93245             (212) 555-7660     Victor Barrister                    5264.27
21144             (917) 555-3287     Julie Barrister                     8205.09
94328             (212) 555-9497     Warren Lee                          3847.88
86092             (518) 555-2803     Ida Olden                           2690.21
22839             (718) 555-8923     John Tillson                        6116.53
72652             (212) 555-0800     Freda Stapleton                     4665.87
45565             (646) 555-2048     Kevin Stapleton                    10510.67
62068             (631) 555-4661     Joseph Kendricks                    1098.24
57010             (718) 555-0330     Donna Dallas                       43928.50
66822             (516) 555-6366     Oliver Roberts                      5792.25
77790             (516) 555-0615     Laura Gavin                         2155.50
48508             (917) 555-4224     Calvin Ellsworth                    3212.30
63937             (917) 555-1854     Zenia Lasher                        1551.28
26262             (212) 555-5639     Paula Harrison                      7794.50
32221             (646) 555-3643     Julie Harris                       38776.50
31471             (631) 555-2783     Garry Lee                           2089.00
77205             (518) 555-1061     Kevin Mickens                       2943.39
45581             (212) 555-5955     Michelle Albertson                  1272.34
83341             (518) 555-3394     Yvonne Quantico                     3563.78
44460             (212) 555-1351     Michelle Harrison                    983.13
86036             (917) 555-7134     Garry Paulson                       3835.47
85361             (631) 555-8346     Victoria Tillson                    2857.27



**************************************************************************************************************

                                    java.util.concurrent.ConcurrentHashMap

          Executing listToConcurrentMap with toConcurrentMap(keyMapper, valueMapper, mergeFunction)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

67169             (516) 555-6804     Queen Tillson                       7217.85
93245             (212) 555-7660     Victor Barrister                    5264.27
21144             (917) 555-3287     Julie Barrister                     8205.09
94328             (212) 555-9497     Warren Lee                          3847.88
86092             (518) 555-2803     Ida Olden                           2690.21
22839             (718) 555-8923     John Tillson                        6116.53
72652             (212) 555-0800     Freda Stapleton                     4665.87
45565             (646) 555-2048     Kevin Stapleton                    10510.67
62068             (631) 555-4661     Joseph Kendricks                    1098.24
57010             (718) 555-0330     Donna Dallas                       43928.50
66822             (516) 555-6366     Oliver Roberts                      5792.25
77790             (516) 555-0615     Laura Gavin                         2155.50
48508             (917) 555-4224     Calvin Ellsworth                    3212.30
63937             (917) 555-1854     Zenia Lasher                        1551.28
26262             (212) 555-5639     Paula Harrison                      7794.50
32221             (646) 555-3643     Julie Harris                       38776.50
31471             (631) 555-2783     Garry Lee                           2089.00
77205             (518) 555-1061     Kevin Mickens                       2943.39
45581             (212) 555-5955     Michelle Albertson                  1272.34
83341             (518) 555-3394     Yvonne Quantico                     3563.78
44460             (212) 555-1351     Michelle Harrison                    983.13
86036             (917) 555-7134     Garry Paulson                       3835.47
85361             (631) 555-8346     Victoria Tillson                    2857.27



**************************************************************************************************************

                                  java.util.concurrent.ConcurrentSkipListMap

   Executing listToConcurrentMap with toConcurrentMap(keyMapper, valueMapper, mergeFunction, mapSupplier)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

21144             (917) 555-3287     Julie Barrister                     8205.09
22839             (718) 555-8923     John Tillson                        6116.53
26262             (212) 555-5639     Paula Harrison                      7794.50
31471             (631) 555-2783     Garry Lee                           2089.00
32221             (646) 555-3643     Julie Harris                       38776.50
44460             (212) 555-1351     Michelle Harrison                    983.13
45565             (646) 555-2048     Kevin Stapleton                    10510.67
45581             (212) 555-5955     Michelle Albertson                  1272.34
48508             (917) 555-4224     Calvin Ellsworth                    3212.30
57010             (718) 555-0330     Donna Dallas                       43928.50
62068             (631) 555-4661     Joseph Kendricks                    1098.24
63937             (917) 555-1854     Zenia Lasher                        1551.28
66822             (516) 555-6366     Oliver Roberts                      5792.25
67169             (516) 555-6804     Queen Tillson                       7217.85
72652             (212) 555-0800     Freda Stapleton                     4665.87
77205             (518) 555-1061     Kevin Mickens                       2943.39
77790             (516) 555-0615     Laura Gavin                         2155.50
83341             (518) 555-3394     Yvonne Quantico                     3563.78
85361             (631) 555-8346     Victoria Tillson                    2857.27
86036             (917) 555-7134     Garry Paulson                       3835.47
86092             (518) 555-2803     Ida Olden                           2690.21
93245             (212) 555-7660     Victor Barrister                    5264.27
94328             (212) 555-9497     Warren Lee                          3847.88



**************************************************************************************************************

                                  java.util.concurrent.ConcurrentSkipListMap

     Executing listToSortedConcurrentMap with toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)

--------------------------------------------------------------------------------------------------------------
Account Number      Phone Number     Name                        Total Purchases
**************************************************************************************************************

21144             (917) 555-3287     Julie Barrister                     8205.09
22839             (718) 555-8923     John Tillson                        6116.53
26262             (212) 555-5639     Paula Harrison                      7794.50
31471             (631) 555-2783     Garry Lee                           2089.00
32221             (646) 555-3643     Julie Harris                       38776.50
44460             (212) 555-1351     Michelle Harrison                    983.13
45565             (646) 555-2048     Kevin Stapleton                    10510.67
45581             (212) 555-5955     Michelle Albertson                  1272.34
48508             (917) 555-4224     Calvin Ellsworth                    3212.30
57010             (718) 555-0330     Donna Dallas                       43928.50
62068             (631) 555-4661     Joseph Kendricks                    1098.24
63937             (917) 555-1854     Zenia Lasher                        1551.28
66822             (516) 555-6366     Oliver Roberts                      5792.25
67169             (516) 555-6804     Queen Tillson                       7217.85
72652             (212) 555-0800     Freda Stapleton                     4665.87
77205             (518) 555-1061     Kevin Mickens                       2943.39
77790             (516) 555-0615     Laura Gavin                         2155.50
83341             (518) 555-3394     Yvonne Quantico                     3563.78
85361             (631) 555-8346     Victoria Tillson                    2857.27
86036             (917) 555-7134     Garry Paulson                       3835.47
86092             (518) 555-2803     Ida Olden                           2690.21
93245             (212) 555-7660     Victor Barrister                    5264.27
94328             (212) 555-9497     Warren Lee                          3847.88

6. Related Article(s)

7. Summary

The Collectors toMap and toConcurrentMap methods fulfill the Map paradigm of the Map, Reduce, Filter cornerstone paradigms of the functional programming methodology. In the case of duplicate keys used in mapping, the use of the mergeFunction was invoked to resolve these conflicts.

8. Download the Source Code

This was an example of the use of collectors to Map and toConcurrentMap to create maps from a list.

Download
You can download the full source code of this example here: Collectors toMap in Java

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments