Java eight - Convert ArrayList to HashMap or LinkedHashMap - Example Tutorial

One of the mutual draw of piece of work inward Java is to convert a List of object e.g. List<T> into a Map e.g. Map<K, V>, where K is but about belongings of the object in addition to V is the actual object. For example, suppose you lot receive got a List<Order> in addition to you lot desire to convert it into a Map e.g. Map<OrderId, Order>, how exercise you lot that? Well, the simplest way to ambit this is iterating over List in addition to add together each chemical constituent to the Map past times extracting keys in addition to using the actual chemical constituent equally an object. This is just many of us exercise it inward pre-Java 8 basis but JDK 8 has made it fifty-fifty simpler. In Java 8, you lot tin acquire the current from List in addition to so collect all elements into a Map past times using a Collector. The collect() method of Stream shape in addition to java.util.stream.Collectors shape gives you lot ample choices to create upwards one's heed which belongings goes into the commutation in addition to which object goes into the value.

Also, In most cases, you lot convert an ArrayList to HashMap or LinkedHashMap, depending upon the scenario, so the occupation of converting a List to Map is genuinely same equally the occupation of converting an ArrayList to HashMap or LinkedHashMap because ArrayList is a List in addition to HashMap is a Map. I'll exhibit you lot an instance of this shortly.

Btw, inward general, when you lot convert a List to a Map, you lot receive got to proceed inward heed but about of the nuisances which come upwards from the fact that they are 2 dissimilar information construction alongside dissimilar properties.

For example, a List is an ordered collection which allows duplicate elements, but Map doesn't provide whatsoever ordering guarantee in addition to it doesn't allow duplicate keys (see Java Fundamentals: Collections). This agency you lot may lose the master social club of objects inward the List if you lot are non careful.

Though, if you lot attention for social club you lot tin opt for a Map implementation which provides but about sort of ordering guarantee e.g. LinkedHashMap which guarantee insertion social club (the social club inward which mappings are added into the map) in addition to TreeMap which is a sorted map, in addition to sort objects inward their natural social club of whatsoever social club imposed past times provided Comparator. See the difference betwixt HashMap, TreeMap, in addition to LinkedHasMap for to a greater extent than details.


Similarly, it may live possible that the List you lot are converting into a Map may comprise but about duplicates, which may non live a occupation inward the traditional way because when you lot insert an existing commutation into the Map, it overwrites the former value, which would live the same object inward instance of duplicate.

But, it does pose a occupation if you lot seek to collect duplicate elements from Stream into a Map, without telling Collector how to resolve the necktie (see From Collections to Streams inward Java 8 Using Lambda Expressions, a costless online Java 8 course of written report from Plurasight).

In short, you lot may acquire "Exception inward thread "main" java.lang.IllegalStateException: Duplicate key" exception piece converting an ArrayList alongside duplicate elements into an HashMap inward Java 8.

You tin solve this occupation past times telling Collector interface nearly how to handgrip duplicates. The toMap() method which we'll utilisation to convert an ArrayList to HashMap is overloaded in addition to it allows you lot to specify which elements to proceed in addition to which chemical constituent to discard inward instance of duplicates.

Enough of theory, now, let's commence coding ...

How to convert ArrayList to HashMap earlier Java 8

This is the classic way to convert a listing to Map inward Java. We are iterating over List using enhanced for loop in addition to inserting String equally a commutation into an HashMap in addition to its length equally a value into HashMap.

This code besides handles whatsoever duplicate inward the listing good because it is using the put() method to insert entries which override values inward instance of duplicate keys but no mistake or exception is thrown.

Map<String, Integer> map = novel HashMap<>();
for(String str: listOfString){
   map.put(str, str.length());
}

In this code, I receive got chosen an HashMap but you lot are costless to conduct whatsoever variety of map e.g. LinkedHashMap or TreeMap depending upon your requirement.

You tin fifty-fifty utilisation a ConcurrentHashMap, if you lot desire to,  Btw, You should utilisation a LinkedHashMap if you lot desire to save social club though.



Converting ArrayList to HashMap inward Java 8 using lambda expression

This is the modern way of converting a listing to map inward Java 8. First, it gets the current from the list in addition to so it calls the collect() method to collect all chemical constituent using a Collector. We are passing a toMap() method to tell Collector that utilisation Map to collect element.

Map<String, Integer> map8 = listOfString.stream().collect(toMap(s -> second , second -> s.length()));

The start declaration of toMap is a commutation mapper in addition to minute is a value mapper. We are using lambda expression which agency top chemical constituent itself equally a key (s -> s) in addition to it's length equally value (s -> s.length), here, s represents the electrical current chemical constituent of Stream, which is String, therefore nosotros are able to telephone yell upwards the length() method.

The Lambda is rattling expert at type inference, you lot tin see What's New inward Java 8, but about other costless course of written report from Pluralsight to larn to a greater extent than nearly lambda seem inward Java.

 One of the mutual draw of piece of work inward Java is to convert a List of object e Java 8 - Convert ArrayList to HashMap or LinkedHashMap - Example Tutorial



Converting ArrayList to HashMap using method reference inward Java 8

Whenever you lot utilisation a lambda expression, pause, in addition to recall if you lot tin supersede lambda alongside a method reference because it makes your code cleaner. Lambda is zip but code in addition to if you lot already receive got a method which does the same matter so you lot tin top the method reference instead of a lambda expression, equally shown here.

HashMap<String, Integer> hash = listOfString.stream()                                                                 .collect(toMap(Function.identity(), String::length, (e1, e2) -> e2, HashMap::new));

You tin run into hither nosotros are passing Function.identity() instead of passing the value itself, but, nosotros are using HashMap, which agency the social club volition non live guaranteed, See the difference betwixt HashMap in addition to LinkedHashMap for to a greater extent than details.


Converting ArrayList to LinkedHashMap inward Java 8

LinkedHashMap<String, Integer> linked = listOfString.stream()
.collect(toMap(
Function.identity(),
String::length,
(e1, e2) -> e2,
LinkedHashMap::new));
System.out.println("generated linkedhashmap:" + linked);
}

}

In this case, nosotros are using LinkedHashMap instead of HashMap, which agency the social club of elements volition live same equally inward List because of LinkedHashMap preserver the insertion order. See Java Fundamentals: Collections, a costless Java course of written report from Pluralsight.



Java Program to convert List to Map inward JDK 8

Earlier I wanted to utilisation a user or domain object similar Order or Book to demonstrate this example, but I decided against it inward favor of String to proceed the programme simple. Since almost every Java developer knows nearly String, it makes the programme much to a greater extent than acceptable in addition to focus remains alone on Java 8 features.

So, nosotros receive got a list of String in addition to we'll generate a map of String keys in addition to their length equally value, sounds interesting right, good it is.

We'll progressively movement from traditional, iterative Java solution to advanced, functional Java 8 solution, starting alongside the lambda expressions in addition to moving to method reference in addition to dealing alongside to a greater extent than practical scenarios similar converting listing alongside duplicate objects in addition to keeping the social club of elements intact inward generated map.


import static java.util.stream.Collectors.toMap;  import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function;  /*  * Java Program to convert a List to Map inward Java 8.  * We'll convert an ArrayList of String to an HashMap  * where commutation is String in addition to value is their length  */ public class Demo {    public static void main(String[] args) throws Exception {      // an ArrayList of String object     List<String> listOfString = new ArrayList<>();     listOfString.add("Java");     listOfString.add("JavaScript");     listOfString.add("Python");     listOfString.add("C++");     listOfString.add("Ruby");      System.out.println("list of string: " + listOfString);      // converting ArrayList to HashMap earlier Java 8     Map<String, Integer> map = new HashMap<>();     for (String str : listOfString) {       map.put(str, str.length());     }      System.out.println("generated map: " + map);      // converting List to Map inward Java 8 using lambda expression     Map<String, Integer> map8 = listOfString.stream().collect(         toMap(s -> s, second -> s.length()));      System.out.println("generated map: " + map);      // using method reference     map8 = listOfString.stream().collect(         toMap(Function.identity(), String::length));      // convert listing alongside duplicate keys to HashMap     listOfString.add("Java");     System.out.println("list of string alongside duplicates: " + listOfString);     HashMap<String, Integer> hash = listOfString.stream()         .collect(             toMap(Function.identity(), String::length, (e1, e2) -> e2,                 HashMap::new));     System.out.println("generated hashmap:" + hash);      // proceed the social club same equally master listing piece conversion     LinkedHashMap<String, Integer> linked = listOfString.stream().collect(         toMap(Function.identity(), String::length, (e1, e2) -> e2,             LinkedHashMap::new));     System.out.println("generated linkedhashmap:" + linked);   }  }  Output: listing of string: [Java, JavaScript, Python, C++, Ruby] generated map: {Java=4, C++=3, JavaScript=10, Ruby=4, Python=6} generated map: {Java=4, C++=3, JavaScript=10, Ruby=4, Python=6} listing of string alongside duplicates: [Java, JavaScript, Python, C++, Ruby, Java] generated hashmap:{Java=4, C++=3, JavaScript=10, Ruby=4, Python=6} generated linkedhashmap:{Java=4, JavaScript=10, Python=6, C++=3, Ruby=4}

From the output, you lot tin run into that the start generated map has lost the order, inward listing Ruby comes concluding but inward the map, Python came last.

Same is truthful for the minute instance because nosotros are non specifying which type of Map we desire to Collectors, therefore it is returning a Map implementation which doesn't provide whatsoever ordering guarantee (see Streams, Collectors, in addition to Optional for Data Processing inward Java 8).

 One of the mutual draw of piece of work inward Java is to convert a List of object e Java 8 - Convert ArrayList to HashMap or LinkedHashMap - Example Tutorial


But, if you lot hold off at the concluding example, the social club of entries inward the Map is same equally they were inward master List because nosotros receive got asked Collectors in addition to toMap() method to collect elements inward a LinkedHashMap which keeps entries inward the social club they are inserted.

Regarding duplicates, you lot tin run into that our list contains duplicate elements, Java came twice earlier quaternary instance but Map doesn't comprise duplicate in addition to it didn't throw whatsoever exception or mistake either because nosotros receive got provided a merge role to toMap() method to conduct betwixt duplicate values.


Important points:

1) You tin utilisation the Function.identity() role if you lot are passing the object itself inward the lambda expression. For example, lambda seem s -> s tin live replaced alongside Function.identity() call.

2) Use the static of import characteristic to import static methods of Collectors e.g. toMap(), this volition simplify your code.

3) The toMap(keyExtractor, valueExtractor) doesn't provide whatsoever guarantee of what variety of map it volition return.

4) If your List contains duplicate elements in addition to you lot are using them equally the commutation so you lot should utilisation toMap(keyMapper, valueMapper, mergeFunction). The merge role used to resolve collisions betwixt values associated alongside the same key, equally supplied to Map.merge(Object, Object, BiFunction). See Java SE 8 for Really impatient to larn to a greater extent than nearly merge() role of Map interface inward Java 8.

 One of the mutual draw of piece of work inward Java is to convert a List of object e Java 8 - Convert ArrayList to HashMap or LinkedHashMap - Example Tutorial


5) If you lot desire to maintain the social club of entries inward the Map same equally inward the master listing so you lot should utilisation the toMap(keyMapper, valueMapper, mergeFunction, mapSupplier) method, where mapSupplier is a role which returns a new, empty Map into which the results volition live inserted. You tin render LinkedHashMap::new using constructor reference to collect lawsuit inward a LinkedHashMap, which guarantees the insertion order.


6) Replace lambda seem alongside method reference for brevity in addition to simplified code.


That's all nearly how to convert a List to Map inward Java 8, peculiarly an ArrayList to HashMap in addition to LinkedHashMap. As I said, it's pretty tardily to exercise that using current in addition to collector.

The Collectors, which is a static utility shape similar to Collections, provide several options to collect elements of a current into the dissimilar type of collection in addition to the toMap() method tin live used to collect elements into a Map.

Though this method is overloaded in addition to past times default doesn't guarantee which type of Map it volition render e.g. HashMap, TreeMap, or LinkedHashMap, you lot demand to tell him nearly that.

Similarly, you lot besides receive got to live mindful of ordering in addition to duplicate elements. If you lot desire the social club of elements should live same equally they are inward the master listing so you lot should utilisation LinkedHashMap equally an accumulator to collect mappings. Similarly, utilisation the toMap() version which allows you lot to bargain alongside duplicate keys.

Other Java 8 articles in addition to tutorials you lot may similar to explore

Thanks for reading this article so far. If you lot genuinely similar this tutorial in addition to my tips so delight portion alongside your friends in addition to colleagues. If you lot receive got whatsoever inquiry or feedback so delight driblet me a note.

Subscribe to receive free email updates:

0 Response to "Java eight - Convert ArrayList to HashMap or LinkedHashMap - Example Tutorial"

Posting Komentar