java list set map interconversion between arrays
- 2020-06-01 09:44:53
- OfStack
java list,set,map, interconversion between arrays
1. Turn set list
Set set = new HashSet( new ArrayList());
2. Turn set list
List list = new ArrayList( new HashSet());
3. Convert the array to list
List stooges = Arrays.asList( "Larry" , "Moe" , "Curly" );
There are three elements in stooges. Note: list cannot perform add operation at this time, otherwise it will be reported "java.lang.UnsupportedOperationException", Arrays.asList () returns List, and it is a fixed-length List, so it cannot be converted to ArrayList, only to AbstractList
The reason is that the asList() method returns the list form of an array, and the returned list is just another view of the array, while the array itself does not disappear, and any operation on the list is ultimately reflected in the array. Therefore, the remove and add methods are not supported
String[] arr = { "1" , "2" };
List list = Arrays.asList(arr);
4. Convert the array to set
int [] a = { 1 , 2 , 3 };
Set set = new HashSet(Arrays.asList(a));
5. Related operations of map.
Map map = new HashMap();
map.put("1" , "a" );
map.put('2' , 'b' );
map.put('3' , 'c' );
System.out.println(map);
// Output all values
System.out.println(map.keySet());
// Output all the keys
System.out.println(map.values());
// will map The value of List
List list = new ArrayList(map.values());
System.out.println(list);
// will map The value of Set
Set set = new HashSet(map.values());
System.out.println(set);
6. Turn list array
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));
Thank you for reading, I hope to help you, thank you for your support of this site!