简体   繁体   English

Java 8 Streams映射和过滤器之间的区别

[英]Java 8 Streams difference between map and filter

Result of both approach are same which is best practise to use. 两种方法的结果相同,这是最佳实践。 I am new bee to java 8. i am little bit confused on stream.map and stream.filter 我是Java 8的新蜂。我对stream.map和stream.filter有点困惑

List<String> alpha =
        Arrays.asList("a", "b", "csddddddddddd",
                "d", "ssdddddddddd", "sw", "we", "wew");

// Java 8
List<String> collect = alpha.stream()
        .map(String::toUpperCase)
        .collect(Collectors.toList());

List<Integer> collect2 = alpha.stream()
        .map(s -> s.length())
        .collect(Collectors.toList());

List<Integer> collect3 = collect2.stream()
        .filter(s -> s > 10)
        .collect(Collectors.toList());

List<Integer> collect4 = collect2.stream()
        .map(s -> {
            Integer temp = 0;
            if (s > 10) {
                temp = s;
            }
            return temp;
        })
        .filter(s -> s > 10)
        .collect(Collectors.toList());

Result of both List are same : 两个列表的结果相同:

[13, 12]
[13, 12]

what is best approach. 什么是最好的方法。 and what is best approach in this regards. 在这方面最好的方法是什么

If you want to filter the elements of a Stream by some condition (ie remove elements that don't satisfy the condition), use filter , not map . 如果Stream某种条件过滤Stream的元素(即,删除不满足条件的元素),请使用filter而不是map

The purpose of map is to convert an element of one type to an element of another type. map的目的是将一种类型的元素转换为另一种类型的元素。

The only reason you get the same results in collect3 and collect4 is that after applying map in collect4 , you apply a filter, which removes all the 0 s produced by map . collect3collect4获得相同结果的唯一原因是,在collect4应用了map collect4 ,您应用了一个过滤器,该过滤器删除了map产生的所有0

The entire .map(s ->{ Integer temp = 0;if(s>10) {temp=s;} return temp;}) call is redundant. 整个.map(s ->{ Integer temp = 0;if(s>10) {temp=s;} return temp;})调用是多余的。 That's a very unreadable and inefficient way to write code. 那是编写代码的一种非常不可读且效率低下的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM