Convert ArrayList to LinkedHashMap in Java


The LinkedHashMap Class is an one type of Hash Map which enables an user to maintain a systematic cronology of the elements present into it. This feature also provides the method of insertion, search and deletion in a quick manner. When we need to convert an array list to a linked hash map, we need to set a key value for this and it reflects as the index of an array list. In terms of the process of the iteration and the data sorting, array list and linked hash map; both are same in nature.

Here is a general example and the possible pseudocode for the process −

Input ArrayList Is Here: { 5, 16, 7, 1997, 2001 }
Output LinkedHashMap Will Be:
Index | Value
 1    |   5
 2    |   16
 3    |   7
 4    |   1997
 5    |   2001
while (i < l1.size()) {l.put(i + 1, l1.get(i));i++;}
Here, "l1" is a particular ArrayList and "l" is represented as the
LinkedHashMap.

Algorithm to Convert an ArrayList to a LinkedHashMap in Java

In this possible algorithm, we are going to show you how to perform a conversion process on an array node to make it a set of linked hash map. By using this algorithm, we are going to build some Java syntax to get a broad view of the problem statement.

  • Step 1 − Start the process.

  • Step 2 − Declare and import some Java packages.

  • Step 3 − Create a public list.

  • Step 4 − Declare some key as value.

  • Step 5 − Create a constructor for the referance value.

  • Step 6 − Assign the value of the declared keys in the list.

  • Step 7 − Return some private variable id.

  • Step 8 − Declare a main public class and method.

  • Step 9 − Declare the argument string.

  • Step 10 − Create an array list.

  • Step 11 − Populate the list value with some data elements.

  • Step 12 − Create and declare a linked hash map value.

  • Step 13 − Declare the object methods.

  • Step 14 − Create the object for the linked hash map value.

  • Step 15 − Declare for and every data element to the linked hash map.

  • Step 16 − Print the value as linked hash map and terminate the process.

Syntax to Convert an ArrayList to a LinkedHashMap in Java

public class Book {
   private Integer bookId;
   private String title;
   private String author;
   //getters, setters, constructors, equals and hashcode omitted
}
HashMap<String,HashMap<String,String>> newMap = new HashMap();
for(HashMap<String,String> record : dataList){
   String key = record.get("rollno").toString();
   newMap.put(key,record);
}
HashMap result = (HashMap<String, HashMap<String, String>>)
listOfHashMaps.stream()
.collect(Collectors.toMap(e-> e.get("roll"),e->e));
list.stream()
.collect(toMap(e->e.get("rollno"), Function.identity()));

In this possible syntax above, we have tried to show you how to perform a conversion process on an array node to make it a set of Linked Hash Map. With these syntax we are heading towards to build some Java codes to solve the problem statement in an efficient manner.

Approaches to Follow

  • Approach 1 − Java program to convert an ArrayList to a LinkedHashMap by using the .entrySet(), .toString, streams, remove(Object key), remove(Object key,Object value) method

  • Approach 2 − Java program to convert an ArrayList to a LinkedHashMap by using the put(), java.util.stream.Collectors and this() method

Approach 1

Use of the .entrySet(), .toString, Streams, Remove(Object key), Remove(Object key,Object Value) Method

Use of .entrySet() Method

In this possible approach, we are going to apply the .entrySet() method approach to perform the conversion of an array list into a set of Linked Hash Map.

List<Student> aListStudent = new ArrayList<Student>();
aListStudent.add(new Student(1, "RUDRA"));
aListStudent.add(new Student(2, "ABONI"));
aListStudent.add(new Student(3, "AHONA"));
aListStudent.add(new Student(4, "ANANDI"));
System.out.println("ArrayList contains are here: " + aListStudent);
Map<Integer, Student> mapStudents =
aListStudent.stream().collect( Collectors.toMap(Student::getId,
student->student));
System.out.println("Map contains are: " + mapStudents);

Example

//Java program to convert an ArrayList to a LinkedHashMap by using the .entrySet() method
import java.util.*;
import java.io.*;
public class ARBRDD{
   public static void main(String[] args){
      LinkedHashMap<Integer, Integer> l = new LinkedHashMap<>();
      ArrayList<Integer> l1 = new ArrayList<>();
      l1.add(12);
      l1.add(16);
      l1.add(7);
      l1.add(1997);
      l1.add(2001);
      int i = 0;
      while (i < l1.size()){
         l.put(i + 1, l1.get(i));
         i++;
      }
      System.out.println("Key Present In The List | Value Of The Element Is");
      for (Map.Entry<Integer, Integer> it :l.entrySet()) {
         System.out.println(" " + it.getKey() + " | " + it.getValue());
      }
   }
}

Output

Key Present In The List | Value Of The Element Is
1 | 12
2 | 16
3 | 7
4 | 1997
5 | 2001

Use of .toString and Streams Method

In this possible approach, we are going to apply the .toString() and Java streams method approach to perform the conversion of an array list into a set of Linked Hash Map.

Example

// Java program to convert ArrayList to LinkedHashMap by using .toString and streams method
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;
class integer{
   private Integer id;
   private String name;
   public integer(Integer id, String name){
      this.id = id;
      this.name = name;
   }
   public Integer getId() { return this.id; }
   public String toString(){
      return "[<" + this.id + "=><" + this.name + ">]";
   }
}
public class ARBRDD{
   public static void main(String[] args){
      List<integer> List = new ArrayList<integer>();
      List.add(new integer(1, "ARB"));
      List.add(new integer(2, "RDD"));
      List.add(new integer(3, "DHAKA"));
      List.add(new integer(4, "KOLKATA"));
      System.out.println("ArrayList contains are here: " + List);
      Map<Integer, integer> HashMap =
      List.stream().collect(Collectors.toMap(
      integer::getId, integer -> integer));
      System.out.println("Map contains from the ArrayList are: " +
      HashMap);
   }
}

Output

ArrayList contains are here:
[[<1=><ARB>], [<2=><RDD>], [<3=><DHAKA>], [<4=><KOLKATA>]]
Map contains from the ArrayList are:
{1=[<1=><ARB>], 2=[<2=><RDD>], 3=[<3=><DHAKA>], 4=[<4=><KOLKATA>]}

Use of Remove(Object key), Remove(Object key,Object Value) Method

In this possible approach, we are going to apply the remove(Object key) and remove(Object key,Object value) method approach to perform the conversion of an array list into a set of Linked Hash Map.

Example

//Java program to convert an ArrayList to a LinkedHashMap and remove the elements from the list by using remove(Object key), remove(Object key,Object value)
import java.util.*;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
public class ARBRDD{
   public static void main(String[] args) {
      Map<String, Integer> travelFareMap = new LinkedHashMap<String,
      Integer>();
      travelFareMap.put("BUS", 1200);
      travelFareMap.put("CAR", 2000);
      travelFareMap.put("TRAIN", 3500);
      travelFareMap.put("AIR PLANE", 14000);
      System.out.println(travelFareMap);
      Integer fareCar = travelFareMap.remove("CAR");
      System.out.println("*************************************");
      System.out.println("Vehicle CAR with fare has been "+fareCar+" removed from the HashMap");
      System.out.println(travelFareMap);
      System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
      boolean isCarRemoved = travelFareMap.remove("TRAIN",3500);
      System.out.println("Did CAR removed from the LinkedHashMap: "+isCarRemoved);
      System.out.println(travelFareMap);
      System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
      boolean isFlightRemoved = travelFareMap.remove("AIR PLANE",14000);
      System.out.println("Did AIR PLANE removed from the LinkedHashMap: "+isFlightRemoved);
      System.out.println(travelFareMap);
      System.out.println("##################END####################");
   }
}

Output

{BUS=1200, CAR=2000, TRAIN=3500, AIR PLANE=14000}
*************************************
Vehicle CAR with fare has been 2000 removed from the HashMap
{BUS=1200, TRAIN=3500, AIR PLANE=14000}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Did CAR removed from the LinkedHashMap: true
{BUS=1200, AIR PLANE=14000}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Did AIR PLANE removed from the LinkedHashMap: true
{BUS=1200}
##################END####################

Approach 2

Using the put(), Java.util.stream.Collectors and This() Method.

Use of the put() Method and Define IllegalArgumentsException

In this possible approach, we are going to apply the put() method approach to perform the conversion of an array list into a set of Linked Hash Map and here we have defined the work of a IllegalArgumentsException also.

private static class CompArrayList extends ArrayList<LinkedHashMap<String,
Comparable>> implements Comparable{
   @Override
   public int compareTo(Object o){
      return 0;
   }
}
ArrayList<LinkedHashMap<String, Comparable>> y = new
ArrayList<LinkedHashMap<String, Comparable>>();
LinkedHashMap<String, Comparable> x = new LinkedHashMap<String, Comparable>();

Example

//Java program to convert two arrays containing keys and values into a Linked Hash Map by using put() method and define IllegalArgumentsException
import java.util.*;
import java.io.*;
import java.util.LinkedHashMap;
public class ARBRDD{
   public static HashMap map(Integer[] keys,
   String[] values){
      int keysSize = keys.length;
      int valuesSize = values.length;
      if (keysSize != valuesSize) {
         throw new IllegalArgumentException( "The Number Of Keys Doesn't Match The Number Of Values.");
      }
      if (keysSize == 0) {
         return new HashMap();
      }
      HashMap<Integer, String> map
      = new HashMap<Integer, String>();
      for (int i = 0; i < keysSize; i++) {
         map.put(keys[i], values[i]);
      }
      return map;
   }
   public static void main(String[] args){
      Integer[] keys = { 1, 2, 3, 4, 5 };
      String[] values
      = { "Welcome", "To", "Kolkata", "From", "Dhaka" };
      Map m = map(keys, values);
      System.out.println(m);
   }
}

Output

{1=Welcome, 2=To, 3=Kolkata, 4=From, 5=Dhaka}

Use of the Java.util.stream.Collectors Method

In this possible approach, we are going to apply the java.util.stream.Collectors method approach to perform the conversion of an array list into a set of Linked Hash Map.

Example

//Java program to convert an ArrayList to a LinkedHashMap by using java.util.stream.Collectors
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
public class ARBRDD{
   public static void main(String[] args){
      List<HashMap<String, String>> input = new ArrayList<>();
      HashMap<String, String> subinput1 = new HashMap<>();
      subinput1.put("name", "name1");
      subinput1.put("rollno", "rollno1");
      input.add(subinput1);
      HashMap<String, String> subinput2 = new HashMap<>();
      subinput2.put("name", "name2");
      subinput2.put("rollno", "rollno2");
      input.add(subinput2);
      HashMap<String, HashMap<String, String>> result = (HashMap<String, HashMap<String, String>>) input.stream()
      .collect(Collectors.toMap(v -> (String) v.get("rollno"), e ->
      e));
      System.out.println(result);
   }
}

Output

{rollno2={name=name2, rollno=rollno2}, rollno1={name=name1, rollno=rollno1}}

Use of the This() Method

In this possible approach, we are going to apply the this() method approach to perform the conversion of an array list into a set of Linked Hash Map.

Example

//Java program to convert an ArrayList to a LinkedHashMap by using THIS methed
import java.util.*;
import java.util.LinkedHashMap;
class Book {
   int id;
   String name,author,publisher;
   int quantity;
   public Book(int id, String name, String author, String publisher, int quantity){
      this.id = id;
      this.name = name;
      this.author = author;
      this.publisher = publisher;
      this.quantity = quantity;
   }
}
public class ARBRDD {
   public static void main(String[] args) {
      Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();
      Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB Publications",8);
      Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill Noida",4);
      Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
      map.put(2,b2);
      map.put(1,b1);
      map.put(3,b3);
      for(Map.Entry<Integer, Book> entry:map.entrySet()){
         int key=entry.getKey();
         Book b=entry.getValue();
         System.out.println(key+" Details:");
         System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
      }
   }
}

Output

2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill Noida 4
1 Details:
101 Let us C Yashwant Kanetkar BPB Publications 8
3 Details:
103 Operating System Galvin Wiley 6

Conclusion

In a Java envoronment, the Linked Hash Map class is a joint implementation process for both linked list and a hash table on the map interface with the proper iteration process. This process inherits the hash map class and mold it into a map interface. Today in this article, we have learned about the various methods how to convert the particular array list to Linked Hash Map set in a Java environment. By using the above mentioned syntax and algorithm we have built some Java codes to explain the problem statement in an efficient manner.

Updated on: 19-Jan-2024

33 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements