java list,set,map,數(shù)組間的相互轉(zhuǎn)換詳解
java list,set,map,數(shù)組間的相互轉(zhuǎn)換詳解
1.list轉(zhuǎn)set
Set set = new HashSet( new ArrayList());
2.set轉(zhuǎn)list
List list = new ArrayList( new HashSet());
3.數(shù)組轉(zhuǎn)為list
List stooges = Arrays.asList( "Larry" , "Moe" , "Curly" );
此時(shí)stooges中有有三個(gè)元素。注意:此時(shí)的list不能進(jìn)行add操作,否則會(huì)報(bào) “java.lang.UnsupportedOperationException”,Arrays.asList()返回的是List,而且是一個(gè)定 長的List,所以不能轉(zhuǎn)換為ArrayList,只能轉(zhuǎn)換為AbstractList
原因在于asList()方法返回的是某個(gè)數(shù)組的列表形式,返回的列表只是數(shù)組的另一個(gè)視圖,而數(shù)組本身并沒有消失,對(duì)列表的任何操作最終都反映在數(shù)組上. 所以不支持remove,add方法的
String[] arr = { "1" , "2" };
List list = Arrays.asList(arr);
4.數(shù)組轉(zhuǎn)為set
int [] a = { 1 , 2 , 3 };
Set set = new HashSet(Arrays.asList(a));
5.map的相關(guān)操作。
Map map = new HashMap();
map.put("1" , "a" );
map.put('2' , 'b' );
map.put('3' , 'c' );
System.out.println(map);
// 輸出所有的值
System.out.println(map.keySet());
// 輸出所有的鍵
System.out.println(map.values());
// 將map的值轉(zhuǎn)化為List
List list = new ArrayList(map.values());
System.out.println(list);
// 將map的值轉(zhuǎn)化為Set
Set set = new HashSet(map.values());
System.out.println(set);
6.list轉(zhuǎn)數(shù)組
List list = Arrays.asList( "a" , "b" );
System.out.println(list);
String[] arr = (String[])list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(arr));
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Java的springcloud Sentinel是什么你知道嗎
這篇文章主要介紹了Java之springcloud Sentinel案例講解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
Mybatis之@ResultMap,@Results,@Result注解的使用
這篇文章主要介紹了Mybatis之@ResultMap,@Results,@Result注解的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
spring boot springjpa 支持多個(gè)數(shù)據(jù)源的實(shí)例代碼
這篇文章主要介紹了spring boot springjpa 支持多個(gè)數(shù)據(jù)源的實(shí)例代碼,需要的朋友可以參考下2018-04-04
MyBatis3用log4j在控制臺(tái)輸出SQL的方法示例
本篇文章主要介紹了MyBatis3用log4j在控制臺(tái)輸出SQL的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01

