Fork me on GitHub

List集合初始化

List集合初始化方式

  1. 常规方式
    List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("3");
    System.out.println("getList1: " + list);
  1. Arrays 工具类
    // 生成的list不可变
    List<String> list = Arrays.asList("1", "2", "3");
    System.out.println("getList2: " + list);
    // 如果要可变需要用ArrayList包装一下
    List<String> numbers = new ArrayList<>(Arrays.asList("1", "2", "3"));
    numbers.add("4");
    System.out.println("numbers: " + numbers);
  1. Collections 工具类
    // 生成的list不可变
    List<String> list = Collections.nCopies(3, "1");
    System.out.println("getList3: " + list);
    // 如果要可变需要用ArrayList包装一下
    List<String> dogs = new ArrayList<>(Collections.nCopies(3, "dog"));
    dogs.add("dog");
    System.out.println("dogs: " + dogs);
  1. Lists 工具类
    List<String> list = Lists.newArrayList("1", "2", "3");
    System.out.println("getList4: " + list);
  1. 匿名内部类
    List<String> list = new ArrayList<String>() {{
         add("1");
         add("2");
         add("3");
    }};
    System.out.println("getList5: " + list);
  1. ImmutableList
    List<String> list = ImmutableList.of("1", "2", "3");
    System.out.println("getList6: " + list);
  1. Java8 Stream
    List<String> list = Stream.of("1", "2", "3").collect(Collectors.toList());
    System.out.println("getList7: " + list);
  1. Java9 List.of
    List<String> list = List.of{"1", "2", "3"};
    System.out.println("getList8: " + list);
posted @ 2020-05-11 11:13  Zz_maker  阅读(255)  评论(0编辑  收藏  举报