在 Java 中將 ArrayList 轉換為 HashSet


要將 ArrayList 轉換為 HashSet,首先建立一個 ArrayList -

List<String> l = new ArrayList<String>();

向 ArrayList 新增元素 -

l.add("Accent");
l.add("Speech");
l.add("Diction");
l.add("Tone");
l.add("Pronunciation");

現在將 ArrayList 轉換為 HashSet -

Set<String> s = new HashSet<String>(l);

以下是如何在 Java 中將 ArrayList 轉換為 HashSet 的示例。

示例

 Live Demo

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
public class Main {
   public static void main(String[] args) {
      List<String> l = new ArrayList<String>();
      l.add("Accent");
      l.add("Speech");
      l.add("Diction");
      l.add("Tone");
      l.add("Pronunciation");
      Set<String> s = new HashSet<String>(l);
      System.out.println("HashSet elements...");
      for (Object ob : s)
      System.out.println(ob);
   }
}

輸出

HashSet elements...
Tone
Pronunciation
Accent
Speech
Diction

更新於: 30-7-2019

962 次瀏覽

開啟你的職業

完成課程,獲取認證

開始
廣告