日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java集合转换_java各种集合的转换

發布時間:2023/12/1 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java集合转换_java各种集合的转换 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

內容:

1、List轉Array? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?2、Array轉List

3、String轉int[],String[](對單個字符)????????4、數組、List、Set、Map相互轉換

5、一行輸入多個元素方法

常用集合:Map、Set、List、Array、String

1、List轉Array:

List list=new ArrayList<>();3、String轉int[],String[](對單個字符)

String[] s1 = new String[list.size()];

list.toArray(strings);

注意:

List.toArray()方法返回的是Object[]?數組,轉起來很麻煩的而且不能對數組(integer[])這樣強轉

必須保證s1大小和list大小相同,否則小了會幫你創建相同大小的String[],大了后面幫你不上null,浪費空間

2、Array轉List:

int[] a = {1,2,3}

List list=new ArrayList<>();

list.addAll(Arrays.asList(a));

注意:

List?list =?Arrays.asList(a);也是可行的,可是此時的list是Arrays下的ArrayList,而不是我們平時用的java.util.ArrayList

list instanceof ArrayList的時候是false;

3、String轉int[],String[](對單個字符)

String轉int[]

String?a ="123456";

int[] b =new int[a.length()];

for(int i = 0;i

b[i]=Integer.parseInt(a.substring(i,i+1));//簡化之處,這樣就不用先charAt()在String.valueOf();

}

String轉String[]

String[] c =a.split(",");

或者像上面的

char轉int

int a = Character.getNumericValue('9');

注意:

string?a ="good",實際在常量詞中是以連續的char 'g','o','d'存在的。如果a = "goods"的話,那么在常量詞就只會多一個‘s’,而不是“goods”

4、數組、List、Set、Map相互轉換

List,Set,數組——》Map

都得一個一個put進去的

List ——》Set:

Set mapKeySet?=?new?HashSet<>(list);

Set——》List:

List mapKeyList = new ArrayList<>(set);

Map——》Set:

//?將Map?的鍵轉化為Set

Set?mapKeySet?=?map.keySet();

//?將Map?的值轉化為Set

Set?mapValuesSet?=newHashSet(map.values());

Set,List——》Array:

用法和注意事項基本都同上第一個標題所講的一樣。

注意:

這里建議用LinkHashMap,其他的Map轉換出來的結果是亂序的,不建議轉換,非要轉換,最好再排下序。

5、一行輸入多個元素方法

Listlist = new ArrayList<>();

Scanner scan = new Scanner(System.in);

String s = scan.nextLine();

String[] ss = s.split(" ");

for (String string : ss) {

list.add(Integer.parseInt(string));

}

System.out.println(list);

總結

以上是生活随笔為你收集整理的java集合转换_java各种集合的转换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。