分析Java8中的stream.map()函数

前言

在实战中学习Java8的特性,并应用在实战中,更容易学习

1. 概念

在Java中,Stream 是 Java 8 中引入的一个新的抽象概念,它允许你以一种更为函数式的方式操作集合数据。Stream 提供了一系列的操作,其中之一是 map() 函数。

map() 函数的主要功能是对流中的每个元素应用一个函数,将其映射为新的元素。这个函数会被应用到流中的每个元素,生成一个新的流,其中包含了应用映射函数后的结果。

对于其源码函数:

<R> Stream<R> map(Function<? super T, ? extends R> mapper);

其中,Function 是一个函数接口,接受一个输入参数并生成一个结果。在 map() 中,它定义了对流中元素的映射关系。T 是输入流的元素类型,而 R 是映射后流的元素类型。

2. Demo

采用list的方式:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapExample {
    
    
    public static void main(String[] args) {
    
    
        List<String> words = Arrays.asList("apple", "banana", "orange", "grape");

        // 使用 map() 将每个字符串映射为其长度
        List<Integer> lengths = words.stream()
                                    .map(String::length)  // 使用方法引用,等价于 s -> s.length()
                                    .collect(Collectors.toList());

        // 打印结果
        System.out.println(lengths);  // 输出: [5, 6, 6, 5]
    }
}

在上述示例中,map(String::length) 将每个字符串映射为其长度,最终得到一个包含每个字符串长度的新的整数流。

最后,通过 collect(Collectors.toList()) 将结果收集到一个列表中。

如果有空值,可以通过filter函数过滤:

public class test1 {
    
    
    public static void main(String[] args) {
    
    
        List<String> words = Arrays.asList("apple", "banana", "orange", "grape", "");

        // 使用 map() 将每个字符串映射为其长度
        List<Integer> lengths = words.stream()
                .map(String::length)  // 使用方法引用,等价于 s -> s.length()
                .filter(value -> value != 0)
                .collect(Collectors.toList());

        // 打印结果
        System.out.println(lengths);  // 输出: [5, 6, 6, 5]
    }
}

也采用set的方式则可以去重:

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class test1 {
    
    
    public static void main(String[] args) {
    
    
        List<String> words = Arrays.asList("apple", "banana", "orange", "grape");

        // 使用 map() 将每个字符串映射为其长度
        Set<Integer> lengths = words.stream()
                .map(String::length)  // 使用方法引用,等价于 s -> s.length()
                .collect(Collectors.toSet());

        // 打印结果
        System.out.println(lengths);  // 输出: [5, 6]
    }
}

还有更花的玩法,等你升级demo!!

猜你喜欢

转载自blog.csdn.net/weixin_47872288/article/details/135375137