java中如何快速创建list和快速创建map


创建list

// 最简单的
List strings = Lists.newArrayList("a", "b", "c", "d", "a");
List strings2 = new ArrayList<>();

// 创建的list是不可变的
List strings = Arrays.asList("a", "b", "c");

// 创建一个正常的list
List strings1 = new ArrayList<>(Arrays.asList("a", "b", "c"));

快速创建一个map

// 正常创建map方法
Map stringStringHashMap1 = new HashMap<>();

// 用谷歌的guava工具,创建的map是不可变的,也就是你不能进行修改
ImmutableMap of = ImmutableMap.of("a", 1, "b", 2, "c", 3);
// guava工具还实现了创建者模式
ImmutableMap build1 = ImmutableMap.builder().put("a", 1).put("b", 4).build();

快速创建一个set

// 用guava 快速创建一个set
ImmutableSet build2 = ImmutableSet.builder().add("a").add("b").build();

将list 转成array

ImmutableList of1 = ImmutableList.of(1, 2, 3, 4);
Integer[] integers = of1.toArray(new Integer[0]);
System.out.println("integers = " +JSONObject.toJSON(integers));

list 去重

// 基本类型去重
List collect = list.stream().distinct().collect(Collectors.toList());

// 对象类型去重
List collect = students.stream()
 	 .collect(
 	          Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getA() + o.getB()))
                                                      ), ArrayList::new)
	 );