当前位置:   article > 正文

Java8 - Streams map()_stream.map

stream.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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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:

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

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

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);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

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());



    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

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());
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

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;
    }


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
[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)]

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/352337
推荐阅读
相关标签
  

闽ICP备14008679号