stream的一些方法

测试类

import com.xd.pojo.Student;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@SpringBootTest
public class StreamTests {

    List<Student> students = new ArrayList<>();

    @BeforeEach
    public void  testInitUser() {
        students.add(new Student(1, 19, "张三", "A", true));
        students.add(new Student(1, 20, "张三", "A", true));
        students.add(new Student(1, 18, "李四", "a", false));
        students.add(new Student(1, 21, "王五", "B", true));
        students.add(new Student(1, 20, "赵六", "b", false));
        students.add(new Student(1, 20, "赵六", "F", false));
        students.add(new Student(1, 20, "赵六", "F", false));
        students.add(new Student(1, 21, "赵六", "F", false));
    }

    @Test
    void testStreamOf() {
       Stream.of(new Student(1, 21, "张三", "1", true), new Student(2, 21, "李四", "2", true)).
               forEach(System.out::println);
    }

    @Test
    void testFilter() {
        students.stream().
                filter(student -> student.getAge() > 20).
                forEach(System.out::println);
    }

    @Test
    void testToList(){
        printStr("toList");
        List<Student> collect = students.stream().
                filter(student -> student.getAge() > 20).
                collect(Collectors.toList());
        collect.forEach(System.out::println);

        printStr("toSet");
        Set<Student> collect1 = students.stream().
                filter(student -> student.getAge() > 20).
                collect(Collectors.toSet());
        collect1.forEach(System.out::println);
    }

    @Test
    void testDistinct() {
        printStr("distinct");
        students.stream().
                distinct().
                forEach(System.out::println);
    }


    /**
     * 一对一转换
     * 一对多转换
     */
    @Test
    void testTrans(){
        printStr("trans use map 一对一转换");

        List<String> list = Arrays.asList("234", "100", "200", "305");
        List<Integer> collect = list.stream().map(Integer::valueOf).collect(Collectors.toList());
        collect.forEach(System.out::println);

        printStr("map 对值进行处理");
        list.stream().map(s -> Integer.parseInt(s) * 10).forEach(System.out::println);

        printStr("flatMap 一对多转换");
        List<String> strs = Arrays.asList(" hello world","Jia Gou Wu Dao ","a", "b");
        List<String> collect1 = strs.stream().flatMap(s -> Arrays.stream(s.split(" "))).collect(Collectors.toList());
        collect1.forEach(System.out::println);

        Arrays.stream("hello world".split(" ")).forEach(System.out::println);
    }

    // 6.peek中间管道,对stream中的每个元素逐个遍历处理,
    // 中间管道必须搭配终止管道一起使用,否则中间管道的操作不会执行。
    @Test
    void testPeek() {
        printStr("peek");
        List<String> list = Arrays.asList(" hello world","Jia Gou Wu Dao ","a", "b");
        list.stream().peek(s -> System.out.println("before: " + s)).map(s -> s.toUpperCase()).peek(s -> System.out.println("after: " + s)).forEach(System.out::println);

        printStr("peek 无终止 不执行");
        list.stream().peek(s -> System.out.println("before: " + s));
    }

    // 7.List或者数组中的值拼接到一个字符串里并以逗号分隔开, Collectors.joining
    @Test
    void testJoining() {
        printStr("join");
        List<String> list = Arrays.asList(" hello world","Jia Gou Wu Dao ","a", "b");
        String collect = list.stream().collect(Collectors.joining(","));
        System.out.println(collect);
    }

//    8.Collectors.averagingInt, 求集合均值
    @Test
    void testverage() {
        printStr("average");
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Double average = list.stream().collect(Collectors.averagingInt(i -> i));
        System.out.println(average);
    }

    // 9.统计信息, Collectors.summarizingInt
    @Test
    void testSummarizingInt() {
        printStr("summarizingInt");
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        IntSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingInt(i -> i));
        System.out.println(summaryStatistics.getMax());
        System.out.println(summaryStatistics.getMin());
        System.out.println(summaryStatistics.getSum());
        System.out.println(summaryStatistics.getAverage());
        System.out.println(summaryStatistics);
    }


    // 10.Collectors.groupingBy
    @Test
    void testGroupingBy() {
        printStr("groupingBy");
        Map<String, List<Student>> collect = students.stream().collect(Collectors.groupingBy(Student::getSex));
        collect.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
    }
    // 11.sorted排序, 默认升序,可自定义排序规则。
    @Test
    void testSortBy() {
        printStr("sortBy asc");
        students.stream().sorted(Comparator.comparing(stu -> stu.getAge())).forEach(System.out::println);

        printStr("sortBy2 desc");
        students.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList()).forEach(System.out::println);

        printStr("sortBy2 desc 换种方法");
        students.stream()
                .distinct()
                .sorted( Comparator.comparing(Student::getAge, Comparator.reverseOrder())).forEach(System.out::println);


        printStr("sortBy2 age sex 多级排序");
        students.stream().sorted(Comparator.comparing(Student::getAge)
                        .thenComparing(Student::getSex, Comparator.reverseOrder()))
                .forEach(System.out::println);

        printStr("在sorted中自定义排序规则.");
        students.stream()
                .distinct()
                .sorted((o1, o2) -> o2.getAge() - o1.getAge()).
                forEach(System.out::println);


        // 字典顺序排序
        printStr("字典顺序.");
        students.stream()
                .distinct()
                .sorted((o1, o2) -> {
                    try {
                        String str1 = new String(o1.getName().getBytes("GB2312"), StandardCharsets.ISO_8859_1);
                        String str2 = new String(o2.getName().getBytes("GB2312"), StandardCharsets.ISO_8859_1);
                        return str1.compareTo(str2);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    return 0;
                }).forEach(System.out::println);
    }

    void printStr(String str){
        System.out.println();
        System.out.println(str);
        System.out.println(String.valueOf("=").repeat(str.length()));
    }
}

模型

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;

    private int age;

    private String name;

    private String sex;

    private boolean option;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容