Java 中將 ArrayList 轉換為 LinkedHashMap


在 Java 中,LinkedHashMap 類 是一種雜湊對映,它允許使用者維護其中元素的有序記錄。此功能還提供了快速插入、搜尋和刪除元素的方法。當我們需要將一個陣列列表 轉換為 LinkedHashMap 時,我們需要為此設定一個鍵值,它會反映為陣列列表的索引。在迭代和資料排序方面,陣列列表和 LinkedHashMap 本質上是相同的。

以下是一個通用示例以及此過程的可能虛擬碼:

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.

Java 中將 ArrayList 轉換為 LinkedHashMap 的演算法

在此可能的演算法中,我們將向您展示如何對陣列節點執行轉換過程以將其轉換為一組 LinkedHashMap。透過使用此演算法,我們將構建一些Java 語法 來全面瞭解問題陳述。

  • 步驟 1 - 開始此過程。

  • 步驟 2 - 宣告並匯入一些 Java 包。

  • 步驟 3 - 建立一個公共列表。

  • 步驟 4 - 宣告一些鍵作為值。

  • 步驟 5 - 為引用值建立一個建構函式。

  • 步驟 6 - 在列表中分配已宣告鍵的值。

  • 步驟 7 - 返回一些私有變數 ID。

  • 步驟 8 - 宣告一個主要的公共類和方法。

  • 步驟 9 - 宣告引數字串。

  • 步驟 10 - 建立一個數組列表。

  • 步驟 11 - 使用一些資料元素填充列表值。

  • 步驟 12 - 建立並宣告一個 LinkedHashMap 值。

  • 步驟 13 - 宣告物件方法。

  • 步驟 14 - 為 LinkedHashMap 值建立物件。

  • 步驟 15 - 宣告每個資料元素到 LinkedHashMap 中。

  • 步驟 16 - 列印 LinkedHashMap 作為值並終止此過程。

Java 中將 ArrayList 轉換為 LinkedHashMap 的語法

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()));

在此可能的語法中,我們試圖向您展示如何對陣列節點執行轉換過程以將其轉換為一組 LinkedHashMap。透過這些語法,我們將努力構建一些 Java 程式碼以有效地解決問題陳述。

遵循的方法

  • 方法 1 - 使用 .entrySet()、.toString、流、remove(Object key)、remove(Object key,Object value) 方法將 ArrayList 轉換為 LinkedHashMap 的 Java 程式

  • 方法 2 - 使用 put()、java.util.stream.Collectors 和 this() 方法將 ArrayList 轉換為 LinkedHashMap 的 Java 程式

方法 1

使用 .entrySet()、.toString、流、Remove(Object key)、Remove(Object key,Object Value) 方法

使用 .entrySet() 方法

在此可能的方法中,我們將應用.entrySet() 方法 來執行將陣列列表轉換為一組 LinkedHashMap 的轉換。

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);

示例

//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());
      }
   }
}

輸出

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

使用 .toString 和流方法

在此可能的方法中,我們將應用 .toString() 和Java 流 方法來執行將陣列列表轉換為一組 LinkedHashMap 的轉換。

示例

// 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);
   }
}

輸出

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>]}

使用 Remove(Object key)、Remove(Object key,Object Value) 方法

在此可能的方法中,我們將應用 remove(Object key) 和 remove(Object key,Object value) 方法來執行將陣列列表轉換為一組 LinkedHashMap 的轉換。

示例

//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####################");
   }
}

輸出

{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####################

方法 2

使用 put()、Java.util.stream.Collectors 和 This() 方法。

使用 put() 方法和定義 IllegalArgumentsException

在此可能的方法中,我們將應用put() 方法 來執行將陣列列表轉換為一組 LinkedHashMap 的轉換,並且在這裡我們還定義了 IllegalArgumentsException 的作用。

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>();

示例

//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);
   }
}

輸出

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

使用 Java.util.stream.Collectors 方法

在此可能的方法中,我們將應用 java.util.stream.Collectors 方法來執行將陣列列表轉換為一組 LinkedHashMap 的轉換。

示例

//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);
   }
}

輸出

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

使用 This() 方法

在此可能的方法中,我們將應用 this() 方法來執行將陣列列表轉換為一組 LinkedHashMap 的轉換。

示例

//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);
      }
   }
}

輸出

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

結論

在 Java 環境中,LinkedHashMap 類是將連結列表和雜湊表結合在 Map 介面上的一個實現過程,並具有適當的迭代過程。此過程繼承 HashMap 類並將其轉換為 Map 介面。在本文中,我們學習瞭如何在 Java 環境中將特定的陣列列表轉換為 LinkedHashMap 集的各種方法。透過使用上述語法和演算法,我們構建了一些 Java 程式碼以有效地解釋問題陳述。

另請參閱: Java 面試問題及答案

更新於: 2024 年 6 月 17 日

1K+ 次檢視

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告