文章目录

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);