文章目录

stream代码片段

拼装sql in 字符串

 String appointIds = rows.stream()
    .map(x -> Optional.ofNullable(x.get("appointid")).orElse("").toString())
    .collect(Collectors.joining("','", "('", "')"));

根据字段对list分组

List<Map<String, Object>> maps = (List<Map<String, Object>>) inMap.get("list");
Map<String, List<Map<String, Object>>> grouped = 
maps.stream().collect(Collectors.groupingBy(e -> e.get("appointid").toString()));

flatMap方法,流扁平化 单词字母去重

List<String> wordList = Arrays.asList("Hello", "World");

List<String> uniqueCharacters = wordList.stream()
        //将每个单词转换为由其字母构成的数组
        .map(word -> word.split(""))
        //将各个生成流扁平化为单个流
        .flatMap(Arrays::stream)
        .distinct()
        .collect(Collectors.toList());
//遍历
uniqueCharacters.forEach(s -> System.out.print(s + " "));

归约 reduce()

List<Integer> numbers = Arrays.asList(1, 2, 3, 4);

int sum = numbers.parallelStream().reduce(0, (a, b) -> a + b);

Optional<Integer> sum = numbers.parallelStream()
//.reduce((a, b) -> a + b)
.reduce(Integer::sum);

Optional<Integer> max = numbers.parallelStream().reduce(Integer::max);

数值流与构建流

IntStream evenNumbers = IntStream.rangeClosed(1, 10).filter(n -> n % 2 == 0);

//生成勾股数 //外层生成0-100的自然数
Stream<int[]> pythagoreanTriples = IntStream.rangeClosed(1, 100).boxed()
//内层再次生成a-100的自然数
.flatMap(a -> IntStream.rangeClosed(a, 100)
//筛选符合勾股定理
.filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
//构建勾股数
.mapToObj(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)})
);

Stream.<Integer>iterate(1, n -> n + 2).limit(5).forEach(System.out::println);

Stream.<Double>generate(Math::random).limit(5).forEach(System.out::println);

Stream.<Double>generate(Math::random).limit(5).map(x -> x * 10).collect(Collectors.toList()).forEach(System.out::println);

对象集合属性去重

List<Person> tempPeopleList = peopleList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getId))), ArrayList::new));

对象集合属性排序

 //属性不能为空
 userList.stream().filter(x -> x.getAge() != null && x.getClazz() != null) .sorted(Comparator.comparing(User::getClazz).reversed().thenComparing(User::getAge))
                .collect(Collectors.toList());

// 属性可以为null
List<User> tempUserList = userList.stream().sorted(Comparator.comparing(User::getAge,Comparator.nullsFirst(Integer::compareTo)).reversed()
  .thenComparing(User::getClazz, Comparator.nullsFirst(Integer::compareTo)))
  .collect(Collectors.toList());