Java8 - Streams map()

Posted 小小工匠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java8 - Streams map()相关的知识,希望对你有一定的参考价值。

文章目录


概述

Stream.map()是Stream最常用的一个转换方法,它把一个Stream转换为另一个Stream

map()方法用于将一个Stream的每个元素映射成另一个元素并转换成一个新的Stream

可以将一种元素类型转换成另一种元素类型。

    /**
     * Returns a stream consisting of the results of applying the given
     * function to the elements of this stream.
     *
     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
     * operation</a>.
     *
     * @param <R> The element type of the new stream
     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
     *               <a href="package-summary.html#Statelessness">stateless</a>
     *               function to apply to each element
     * @return the new stream
     */
    <R> Stream<R> map(Function<? super T, ? extends R> mapper);

map()方法接收的对象是Function接口对象,它定义了一个apply()方法,负责把一个T类型转换成R类型。

其中,Function的定义为

@FunctionalInterface
public interface Function<T, R> 

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);  //   将T类型转换为R:

	....
	....
	....




Case 1 : A List of Strings to Uppercase

/**
     * A List of Strings to Uppercase
     */
    public static void StringsListToUppercase() 
        List<String> list = Arrays.asList("a", "b", "c", "d");

        // before java 8
        List<String> newList = new ArrayList<>();
        for (String str : list) 
            newList.add(str.toUpperCase());
        
        System.out.println(newList);

        // java 8
        List<String> collect = list.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println(collect);

        // Extra, streams apply to any data type.
        List<Integer> integers = Arrays.asList(1, 2, 3, 4);
        List<Integer> collect1 = integers.stream().map(t -> t * 2).collect(Collectors.toList());
        System.out.println(collect1);

    

Case 2 : List of objects -> List of String

 /**
     * List of objects -> List of String
     */
    public static void objectsListToStringList() 
        List<Artisan> artisanList = Arrays.asList(
                new Artisan("小A", 18, new BigDecimal(100)),
                new Artisan("小B", 19, new BigDecimal(200)),
                new Artisan("小C", 20, new BigDecimal(300)));

        // Before Java 8
        List<String> nameList = new ArrayList<>();
        for (Artisan artisan : artisanList) 
            nameList.add(artisan.getName());
        
        log.info(nameList.toString());

        // Java 8
        List<String> collect = artisanList.stream().map(Artisan::getName).collect(Collectors.toList());
        log.info(collect.toString());



    

Case 3 : List of objects -> List of other objects

/**
     * List of objects -> List of other objects
     */
    public static void objectsListToOtherObjectsList() 

        List<Artisan> artisanList = Arrays.asList(
                new Artisan("小A", 18, new BigDecimal(100)),
                new Artisan("小B", 19, new BigDecimal(200)),
                new Artisan("小C", 20, new BigDecimal(300)));

        // Before Java 8
        List<ArtisanOther> convert2OtherList = new ArrayList<>();

        for (Artisan artisan : artisanList) 
            ArtisanOther artisanOther = new ArtisanOther();
            artisanOther.setAge(artisan.getAge());
            artisanOther.setName(artisan.getName());

            if ("小C".equals(artisan.getName())) 
                artisanOther.setOtherInfo("Only For 小C");
            
            convert2OtherList.add(artisanOther);
        
        log.info(convert2OtherList.toString());

        // Java 8
        artisanList.stream().map(artisan -> 
            ArtisanOther artisanOther = new ArtisanOther();
            artisanOther.setAge(artisan.getAge());
            artisanOther.setName(artisan.getName());

            if ("小C".equals(artisan.getName())) 
                artisanOther.setOtherInfo("Only For 小C");
            
            return artisanOther;
        ).collect(Collectors.toList());
        log.info(convert2OtherList.toString());
    


Test

    public static void main(String[] args) 
        // A List of Strings to Uppercase
        StringsListToUppercase();

        // List of objects -> List of String
        objectsListToStringList();

        // List of objects -> List of other objects
        objectsListToOtherObjectsList();
    


	
  // 俩内部类 
  @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class Artisan 
        private String name;
        private int age;
        private BigDecimal salary;
    

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class ArtisanOther 
        private String name;
        private int age;
        private String otherInfo;
    


[A, B, C, D]
[A, B, C, D]
[2, 4, 6, 8]
21:57:13.914 [main] INFO com.artisan.java8.stream2.StreamMap - [A,B,C]
21:57:13.918 [main] INFO com.artisan.java8.stream2.StreamMap - [A,B,C]
21:57:13.919 [main] INFO com.artisan.java8.stream2.StreamMap - [StreamMap.ArtisanOther(name=A, age=18, otherInfo=null), StreamMap.ArtisanOther(name=B, age=19, otherInfo=null), StreamMap.ArtisanOther(name=C, age=20, otherInfo=Only ForC)]
21:57:13.920 [main] INFO com.artisan.java8.stream2.StreamMap - [StreamMap.ArtisanOther(name=A, age=18, otherInfo=null), StreamMap.ArtisanOther(name=B, age=19, otherInfo=null), StreamMap.ArtisanOther(name=C, age=20, otherInfo=Only ForC)]

以上是关于Java8 - Streams map()的主要内容,如果未能解决你的问题,请参考以下文章

Java 8 Streams - 分组为单个值[重复]

使用Java8 Stream API对Map按键或值进行排序

使用 Java-8 Streams API 将字符串列表转换为 Map

通俗易懂,java8 .stream().map().collect()用法

通俗易懂,java8 .stream().map().collect()用法

通俗易懂,java8 .stream().map().collect()用法