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' ); 
//  Output all values   
//  Output all the keys   
//  will map The value of List  
List list = new ArrayList(map.values()); 
//  will map The value of Set  
Set set = new HashSet(map.values()); 

6. Turn list array

List list = Arrays.asList( "a" , "b" ); 
String[] arr = (String[])list.toArray(new String[list.size()]); 

Thank you for reading, I hope to help you, thank you for your support of this site!

Related articles: