数组之间的相互转换
List转Set
Set set = new HashSet(new ArrayList());
Set转List
List list = new ArrayList(new HashSet());
数组转为List
List arr = Arrays.asList("1", "2", "3");
//或者
String[] arr = {"1", "2"};
List list = Arrays.asList(arr);
数组转为Set
int[] arr = { 1, 2, 3 };
Set set = new HashSet(Arrays.asList(arr));
Map的值转化为List
List list = new ArrayList(map.values());
Map的值转化为Set
Set set = new HashSet(map.values());
List转数组
List list = Arrays.asList("a","b");
String[] arr = (String[])list.toArray(new String[list.size()]);
代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Test {
private static List<String> arrayList;
private static Map<String, String> hashMap;
private static Set<String> hashSet;
private static String[] arr = { "11oneone", "22twotwo" };
public static void main(String[] args) {
//list转set
/*
initList();
Set<String> set = new HashSet<String>(arrayList);
System.out.println("arrayList.toString()--->" + set.toString());
System.out.println("set.toString()--->" + set.toString());
*/
//set转list
/*
initSet();
List<String> list = new ArrayList<String>(hashSet);
System.out.println("hashSet.toString()--->"+hashSet.toString());
System.out.println("list.toString()--->"+list.toString());
*/
// 数组转为list
/*
List<String> list = Arrays.asList(arr);
System.out.println("list.toString()--->"+list.toString());
*/
//数组转set
/*
Set set = new HashSet(Arrays.asList(arr));
System.out.println("set.toString()--->"+set.toString());
*/
//map的值转为list
/*
initMap();
List<String> list = new ArrayList<String>(hashMap.values());
System.out.println("list.toString()--->"+list.toString());
*/
//map的值转为set
/*
initMap();
Set<String> set = new HashSet<String>(hashMap.values());
System.out.println("set.toString()--->"+set.toString());
*/
//map的key转为set
/*initMap();
Set<String> set = new HashSet<String>(hashMap.keySet());
System.out.println("set.toString()--->"+set.toString());
*/
//list转数组
initList();
String[] arr1 = (String[]) arrayList.toArray(new String[arrayList.size()]);
System.out.println("Arrays.toString(arr1)--->" + Arrays.toString(arr1));
}
public static void initList() {
arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
}
public static void initMap() {
hashMap = new HashMap<String, String>();
hashMap.put("one", "one1");
hashMap.put("two", "two2");
hashMap.put("three", "three3");
}
public static void initSet() {
hashSet = new HashSet<String>();
hashSet.add("1one");
hashSet.add("2two");
hashSet.add("3three");
hashSet.add("4four");
hashSet.add("5five");
}
}