1

1. 数组与List

1. List -> 数组

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        list.add("i=" + i);
    }
    
    //1. 通过toArray方法
    String[] array = list.toArray(new String[0]);
    
    //2. stream
    String[] array2 = list.stream().toArray(String[]::new);
    
    System.out.println(Arrays.toString(array));
    System.out.println(Arrays.toString(array2));
}

2. 数组 -> List

public static void main(String[] args) {
    String[] str =new String[] {"aaa","bbb","ccc","ddd"};
    List<String> list2 = new ArrayList<>();
    //1. Arrays.asList()
    List<String> list = Arrays.asList(str);

    //2. Collections.addAll(list, arrays)
    Collections.addAll(list2, str);
    
    //3. stream
    List<String> list3 = Stream.of(str).collect(Collectors.toList());
    
    System.out.println(list.toString());
    System.out.println(list2.toString());
    System.out.println(list3.toString());
}

2. 数组与Set

1. 数组 -> Set

public static void main(String[] args) {
    String[] str =new String[] {"aaa","bbb","ccc","ddd"};
    
    //1. 通过先转List之后引入Set
    Set<String> set = new HashSet<>(Arrays.asList(str));
    
    //2. stream
    Set<String> set2 = Stream.of(str).collect(Collectors.toSet());
    
    System.out.println(set);
    System.out.println(set2);
}

2. Set -> 数组

public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    set.add("aaa");
    set.add("bbb");
    set.add("ccc");
    set.add("ddd");
    
    //1. 通过 toArray()
    String[] array = set.toArray(new String[0]);
    //2. stream
    String[] array2 = set.stream().toArray(String[]::new);
    
    System.out.println(Arrays.toString(array));
    System.out.println(Arrays.toString(array2));
}

3. List与Set

1. List -> Set

public static void main(String[] args) {

List<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");

Set<String> set = new HashSet<>(list);

Set<String> set2 = list.stream().collect(Collectors.toSet());

System.out.println(set.toString());
System.out.println(set2.toString());

}

2. Set -> List

public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    set.add("aaa");
    set.add("bbb");
    set.add("ccc");
    set.add("ddd");
    
    //1. list构造方法
    List<String> list = new ArrayList<>(set);
    
    //2. stream 
    List<String> list2 = set.stream().collect(Collectors.toList());
    
    System.out.println(list.toString());
    System.out.println(list2.toString());
}

wo0o0o0o0
53 声望2 粉丝

« 上一篇
JDK动态代理