java中List、Array、Map、Set等集合相互转换

 在java中,我们经常需要对List、Array等做一些转换操作,当然转换方法有很多种,但哪种方法既方便又高效呢?在这里向大家介绍一下集合间的最佳转换方法。

 

1.List转换为Array

List list = new ArrayList();
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 list = new ArrayList(map.values());

 

4.Array转换为Set

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

5.Map转换为Set

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

 

你可能感兴趣的:(java基础知识,java)