JAVA中数组(Array)、字符串(String)、集合(List、Set)相互转换

 

1、数组转List

String[] arr = new String[]{"A", "B", "C"};
List list = Arrays.asList(arr);        //返回固定大小,不能做add和remove等操作

  

2、数组转Set

String[] arr= new String[]{"A", "B", "C"};
Set<String> set= new HashSet<>(Arrays.asList(arr));  //可以直接对set进行add和remove操作

  

3、List转数组 

String[] arr= new String[]{"A", "B", "C"}; 
List list = Arrays.asList(arr);     
Object[] result = list.toArray();   //使用toArray()方法

 

另外一种

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>
byte[] bytes=Bytes.toArray(list);

 

 

 

4、List转Set

String[] arr= new String[]{"A", "B", "C"};
List list = Arrays.asList(arr);
Set result = new HashSet(list);   //list转set

 

5、Set转数组

String[] arr= new String[]{"A", "B", "C"};
Set<String> set= new HashSet<>(Arrays.asList(arr));
Object[] result = set.toArray();        //使用toArray()方法

 

6、Set转List

String[] arr= new String[]{"A", "B", "C"};
Set<String> set= new HashSet(Arrays.asList(arr));
List<String> result = new ArrayList<>(set);  

 

posted @ 2020-03-12 17:18  yvioo  阅读(9379)  评论(0编辑  收藏  举报