java中List、Array、Map、Set等集合相互轉換

 在java中,我們經常需要對List、Array等做一些轉換操作,當然轉換方法有很多種,但哪種方法既方便又高效呢?在這裏向大家介紹一下集合間的最佳轉換方法。

 

1.List轉換爲Array

List<String> list = new ArrayList<String>();
list.add("China");
list.add("Switzerland");
list.add("Italy");
list.add("France");
String [] countries = list.toArray(new String[list.size()]);

 

2.Array轉換爲List:

String[] countries = {"China", "Switzerland", "Italy", "France"};
List list = Arrays.asList(countries);

 

3.Map轉換爲List:

List<Value> list = new ArrayList<Value>(map.values());

 

4.Array轉換爲Set

String [] countries = {"India", "Switzerland", "Italy"};      
Set<String> set = new HashSet<String>(Arrays.asList(countries));
System.out.println(set);

5.Map轉換爲Set

Map<Integer, String> sourceMap = createMap();
Set<String> targetSet = new HashSet<>(sourceMap.values());

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章