java中List、Array、Map、Set等集合相互轉換
在java中,我們經常需要對List、Array等做一些轉換操作,當然轉換方法有很多種,但哪種方法既方便又高效呢?在這里向大家介紹一下集合間的最佳轉換方法。
1.List轉換為Array
1
2
3
4
5
6
|
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
1
2
|
String[] countries = { "China" , "Switzerland" , "Italy" , "France" }; List list = Arrays.asList(countries); |
3.Map轉換為List
1
|
List<Value> list = new ArrayList<Value>(map.values()); |
4.Array轉換為Set
1
2
3
|
String [] countries = { "India" , "Switzerland" , "Italy" }; Set<String> set = new HashSet<String>(Arrays.asList(countries)); System.out.println(set); |
5.Map轉換為Set
1
2
|
Map<Integer, String> sourceMap = createMap(); Set<String> targetSet = new HashSet<>(sourceMap.values()); |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/suifeng3051/article/details/41699033