常用Stream之sorted、peek、map、Collectors等

一、流的各种操作

下面没有详细介绍,看看用法就明白了。

public class StreamDemo {
    public static void main(String[] args) {
        /**
         * Collection 下的 stream() 和 parallelStream() 方法
         */
        List list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        // 获取一个顺序流
        Stream stream = list.stream();
        String s = stream.collect(Collectors.joining()).toString();
        System.out.println("stream.collect(Collectors.joining()): " + s);


        // 获取一个并行流 多线程的:如果比较耗时的操作,可以使用这个,如果是纯cpu计算,使用for性能更高
        Stream stringStream = list.parallelStream();

        /**
         *  使用 Arrays 中的 stream() 方法,将数组转成流
         */
        Integer[] nums = new Integer[10];
        Stream stream1 = Arrays.stream(nums);


        /**
         *  使用Stream中的静态方法:of()、iterate()、generate()
         *
         */
        Stream integerStream = Stream.of(1, 2, 3, 4, 5, 6);

        Stream limit = Stream.iterate(0, x -> x + 2).limit(6);
        limit.forEach(System.out :: println);


        Stream.generate(Math::random).limit(2).forEach(System.out :: println);

        // 筛选与切片
        Stream integerStream1 = Stream.of(6, 4, 3, 5, 1, 8, 1, 9, 0, 1, 3, 2);
        Stream limit1 = integerStream1
                .filter(m -> m > 5)
                .distinct()
                .limit(3);
        System.out.println("筛选与切片");
        limit1.forEach(System.out :: println);

        /**
         *  映射
         *  map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
         *  latMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
         */
        List listArray = Arrays.asList("a,b,c", "1,2,3", "d,2,d");
        // 将每个元素转成一个新的且不带逗号的元素
        Stream stringStream1 = listArray
                .stream()
                .map(a -> a.replaceAll(",", ""));
        stringStream1.forEach(forS -> {
            System.out.println(forS);
        });

        System.out.println("====flatMap===");
        Stream s3 = listArray.stream().flatMap(flat -> {
            // 将每个元素转换成一个stream
            String[] split = flat.split(",");
            Stream stream2 = Arrays.stream(split);
            return stream2;
        });
        s3.forEach(sFlat -> System.out.println(sFlat));

        System.out.println("====排序sorted===");

        List aslists = Arrays.asList("hello", "felord.cn");
        aslists.stream().sorted().forEach(sor -> {
            System.out.println(sor);
        });

        // 正确操作!!!!!
        System.out.println("===peek===");
        aslists.stream().peek(pee -> {
            System.out.println(pee);
        }).collect(Collectors.toList());

    }
}

二、Collectors工具库

@Data
@AllArgsConstructor
public class Student {
    String name;
    int age;
    int type;
}
public class StreamCollector {
    public static void main(String[] args) {
        Student s1 = new Student("aa", 10, 2);
        Student s2 = new Student("bb", 50, 6);
        Student s3 = new Student("cc", 30, 1);
        Student s4 = new Student("dd", 40, 7);

        List list = Arrays.asList(s1, s2, s3, s4);
        // 装成list
        List collect = list.stream().map(Student::getAge).collect(Collectors.toList());
        // 转成set
        Set collect1 = list.stream().map(Student::getAge).collect(Collectors.toSet());
        // 转成map,注:key不能相同,否则报错
        Map collect2 = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge));
        // 字符串分隔符连接
        String collect3 = list.stream().map(Student::getName).collect(Collectors.joining("*", "【", "】"));
        // 聚合操作
        // 1.学生总数
        Long collect4 = list.stream().collect(Collectors.counting());
        // 2.最大年龄 (最小的minBy同理)
        Integer integer = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get();
        // 3.所有人的年龄
        Integer collect5 = list.stream().collect(Collectors.summingInt(Student::getAge));
        // 4.平均年龄
        Double collect6 = list.stream().collect(Collectors.averagingDouble(Student::getAge));
        // 带上以上所有方法
        DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
        System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());


        // 分组
        Map> collect7 = list.stream().collect(Collectors.groupingBy(params -> params.getAge()));
        // 多重分组,先根据类型分再根据年龄分
        Map>> collect8 = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));

        // 分区
        // 分成两部分,一部分大于10岁,一部分小于等于10岁
        Map> collect9 = list.stream().collect(Collectors.partitioningBy(param -> param.getAge() > 25));

        // 规约
        Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get();

        // 打印看下
        System.out.println("1. Collectors.toList(): " + collect);
        System.out.println("2. Collectors.toSet(): " + collect1);
        System.out.println("3. Collectors.toMap: " + collect2);
        System.out.println("4, Collectors.joining: " + collect3);
        System.out.println("5. Collectors.counting(): " + collect4);

        System.out.println("6. Collectors.maxBy: " + integer);
        System.out.println("7. Collectors.summingInt: " + collect5);
        System.out.println("8. Collectors.averagingDouble: " + collect6);
        System.out.println("9. Collectors.groupingBy: " + collect7);
        System.out.println("10. Collectors.groupingBy多重分组: " + collect8);
        System.out.println("11. Collectors.partitioningBy: " + collect9);
        System.out.println("12. Collectors.reducing: " + allAge);

    }
}

三、附加

将字符串格式的 “true” 和 “false” 转换为boolean类型的:

public static void main(String[] args) {
        Map map = new HashMap();
        String param = "0,true;1,true;2,true;15,true;7,false";
        String[] split = param.split(";");
        Arrays.stream(split).forEach(s -> {
            map.put(s.split(",")[0], s.split(",")[1]);
        });

        System.out.println(map);

        String s1 = "true";
        String s2 = "false";
        String s3 = "True";
        String s4 = "False";
        // 都是false
        System.out.println(Boolean.getBoolean(s1));
        System.out.println(Boolean.getBoolean(s2));
        System.out.println(Boolean.getBoolean(s3));
        System.out.println(Boolean.getBoolean(s4));


        System.out.println("========");
        // 正确返回了
        System.out.println(Boolean.parseBoolean(s1));
        System.out.println(Boolean.parseBoolean(s2));
        System.out.println(Boolean.parseBoolean(s3));
        System.out.println(Boolean.parseBoolean(s4));

    }

需求中遇到的,作为一个记录,很简单。

你可能感兴趣的:(java技术架构学习-new,java,算法,jvm)