简要介绍list和map有参数时如何初始化、集合在jdk8中如何使用stream流使代码更简洁高效。
集合的初始化
无参数初始化这里就不介绍了,简要说明有参数的。
数组
int[] ints = {1, 2, 3};
List
# 方式一:推荐、速度快List<String> strings = new ArrayList<>(Arrays.asList("123", "123"));# 方式二:备用List<String> strings2 = new ArrayList<String>() {{add("123");add("string");}};System.out.println(strings2);
Map
HashMap<String, String> map = new HashMap<String, String>() {{put("name", "test");put("age", "20");}};
stream流
jdk8新特性,类似C#的linq,可以对集合进行sql操作。
过滤、排序、转换集合
# 案例一:过滤、排序List<Item> collect1 = items.stream().filter(name -> name.getPrice() > 100).sorted((x, y) -> y.getPrice() - x.getPrice()).collect(Collectors.toList());# 案例二:转换新集合items.stream().filter(name -> name.getPrice() > 100).sorted((x, y) -> y.getPrice() - x.getPrice()).map(item -> item.getPrice()).collect(Collectors.toList());# 案例三:统计,可以获取最大、最下、评价值、求和items.stream().filter(name -> name.getPrice() > 100).sorted((x, y) -> {return y.getPrice() - x.getPrice();}).distinct() // 去重复.mapToInt(x -> x.getPrice()).summaryStatistics();# 案例四:拼接字符串strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", "));
去重
简单去重
List unique = list.stream().distinct().collect(Collectors.toList());
复杂对象去重
// 根据name,sex两个属性去重List<Person> unique = persons.stream().collect(Collectors. collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new));
