java stream用法

public class StreamProject {

    private List<Student> students;

    @Before
    public void before(){
        students=new ArrayList<>();
        for(int i=0;i<5;i++){
            Student student=new Student();
            student.setAge(i);
            student.setId(Long.parseLong(String.valueOf(i)));
            student.setName("xiao"+i);
            students.add(student);
        }
    }
    /**
     * map 把 input Stream 的每一个元素,映射成 output Stream 的另外一个元素。
     */
    @Test
    public void test1(){
        List<String> wordList= Arrays.asList("ni","hao","hello");
        List<String> output = wordList.stream().map(String::toUpperCase).collect(Collectors.toList());
        output.forEach(System.out::println);
    }

    /**
     * filter 对原始 Stream 进行某项测试,通过测试的元素被留下来生成一个新 Stream
     */
    @Test
    public void test2(){
        Integer[] sixNums = {1, 2, 3, 4, 5, 6};
        Integer[] evens = Stream.of(sixNums).filter(n -> n%2 == 0).toArray(Integer[]::new);
        Arrays.stream(evens).forEach(System.out::println);
    }

    /**
     *  forEach 方法接收一个 Lambda 表达式,然后在 Stream 的每一个元素上执行该表达式。
     *  forEach 是 terminal 操作,因此它执行后,Stream 的元素就被“消费”掉了,你无法对一个 Stream 进行两次 terminal 运算
     */
    @Test
    public void test3(){
        students.stream().filter(student -> student.getAge()>1).forEach(student -> System.out.println(student.getName()));
    }

    /**
     *  具有相似功能的 intermediate 操作 peek 可以多次操作
     *  peek 对每个元素执行操作并返回一个新的 Stream
     */
    @Test
    public void test4(){
        Stream.of("one", "two", "three", "four")
            .filter(e -> e.length() > 3)
            .peek(e -> System.out.println("Filtered value: " + e))
            .map(String::toUpperCase)
            .peek(e -> System.out.println("Mapped value: " + e))
            .collect(Collectors.toList());
    }

    /**
     * findFirst总是返回 Stream 的第一个元素,或者空。
     * 这里比较重点的是它的返回值类型:Optional。使用它的目的是尽可能避免 NullPointerException。
     */
    @Test
    public void test5(){
        String strA = " abcd ", strB = null;
        print(strA);
        print("");
        print(strB);
        System.out.println(getLength(strA));
        System.out.println(getLength(""));
        System.out.println(getLength(strB));
    }
    public static void print(String text) {
        // Java 8
        Optional.ofNullable(text).ifPresent(System.out::println);
        // Pre-Java 8
//        if (text != null) {
//            System.out.println(text);
//        }
    }
    public static int getLength(String text) {
        // Java 8
        return Optional.ofNullable(text).map(String::length).orElse(-1);
        // Pre-Java 8
        // return if (text != null) ? text.length() : -1;
    };

    /**
     * reduce这个方法的主要作用是把 Stream 元素组合起来。
     */
    @Test
    public void test6(){
        // 字符串连接,concat = "ABCD"
        String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
        System.out.println(concat);
        // 求最小值,minValue = -3.0
        double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce( Double::min).get();
        System.out.println(minValue);
        // 求和,sumValue = 10, 有起始值
        int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
        System.out.println(sumValue);
        // 求和,sumValue = 10, 无起始值
        sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();
        System.out.println(sumValue);
        // 过滤,字符串连接,concat = "ace"
        concat = Stream.of("a", "B", "c", "D", "e", "F").filter(x -> x.compareTo("Z") > 0).reduce("", String::concat);
        System.out.println(concat);
    }

    /**
     *limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素
     */
    @Test
    public void test7(){
        List<String> names=students.stream().map(Student::getName).limit(3).skip(1).collect(Collectors.toList());
        System.out.println(names);
    }
    /**
     *对 Stream 的排序通过 sorted 进行
     * 它比数组的排序更强之处在于你可以首先对 Stream 进行各类 map、filter、limit、skip 甚至 distinct 来减少元素数量后,
     * 再排序,这能帮助程序明显缩短执行时间。
     */
    @Test
    public void test8(){
        List<Student> students2=students.stream().limit(3).sorted((s1,s2) ->s2.getName().compareTo(s1.getName()))
            .peek(System.out::println)
            .collect(Collectors.toList());
        List<Student> students3=students.stream().limit(3).sorted((s1,s2) ->Integer.valueOf(s1.getAge()).compareTo(Integer.valueOf(s2.getAge())))
            .peek(System.out::println)
            .collect(Collectors.toList());
    }
    /**
     * min/max/distinct min 和 max 的功能也可以通过对 Stream 元素先排序,再 findFirst 来实现,
     * 但min 和 max 的性能会更好,为 O(n),而 sorted 的成本是 O(n log n)。
     * 同时它们作为特殊的 reduce 方法被独立出来也是因为求最大最小值是很常见的操作。
     */
    @Test
    public void test9() throws Exception {
        BufferedReader br=new BufferedReader(new FileReader("E:\\学习\\新建文本文档 (5).txt"));
        int longest=br.lines().mapToInt(String::length).max().getAsInt();
        br.close();
        System.out.println(longest);
    }

    /**
     * 找出全文的单词,转小写,并排序
     * @throws Exception
     */
    @Test
    public void test91() throws Exception {
        BufferedReader br=new BufferedReader(new FileReader("E:\\学习\\新建文本文档 (5).txt"));
        List<String> words=br.lines().flatMap(line-> Stream.of(line.split(" "))).filter(word->word.length()>0)
            .map(String::toLowerCase).distinct().sorted().collect(Collectors.toList());
        br.close();
        System.out.println(words);
    }
    /**
     *Stream 有三个 match 方法,从语义上说:
     allMatch:Stream 中全部元素符合传入的 predicate,返回 true
     anyMatch:Stream 中只要有一个元素符合传入的 predicate,返回 true
     noneMatch:Stream 中没有一个元素符合传入的 predicate,返回 true
     它们都不是要遍历全部元素才能返回结果。例如 allMatch 只要一个元素不满足条件,就 skip 剩下的所有元素,返回 false。
     */
    @Test
    public void test10(){
        boolean a=students.stream().allMatch(student -> student.getAge()>3);
        System.out.println(a);
    }
    /**
     *flatMap 一对多
     */
    @Test
    public void test11(){
        Stream<List<Integer>> inputStream = Stream.of(
            Arrays.asList(1),
            Arrays.asList(2, 3),
            Arrays.asList(4, 5, 6)
        );
        //inputStream.forEach(System.out::println);
        inputStream.flatMap((childList) -> childList.stream()).forEach(System.out::println);
    }
    /**
     *Stream.generate
     */
    @Test
    public void test12(){
        Random ran=new Random();
        Supplier<Integer> ins=ran::nextInt;
        Stream.generate(ins).limit(10).forEach(System.out::println);
        //Another way
        IntStream.generate(() -> (int) (System.nanoTime() % 100)).
            limit(10).forEach(System.out::println);

    }

}
public class Student {
    private Long id;
    private String name;
    private int age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}';
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值