zoukankan      html  css  js  c++  java
  • Java——Stream map

    一、介绍

    在Java 8中,Stream的map方法可以将对象转化为其他对象。

    二、例子

    2.1、大写字符串列表

    List<String> list = new ArrayList<>();
    Collections.addAll(list, "a", "b", "c");
    list = list.stream().map(String::toUpperCase).collect(Collectors.toList());
    System.out.println(list);   // [A, B, C]
    

    2.2、对象列表 -> 字符串列表

    List<Student> list = new ArrayList<>();
    Student stu1 = new Student("张三", 10);
    Student stu2 = new Student("李四", 30);
    Student stu3 = new Student("王五", 20);
    Collections.addAll(list, stu1, stu2 ,stu3);
    List<String> newList = list.stream().map(stu -> stu.getName()).collect(Collectors.toList());
    System.out.println(newList);   // [张三, 李四, 王五]
    

    2.3、对象列表 -> 其他对象列表

    // Student.java
    public class Student {
        private String name;
        private int age;
        //...
    }
    
    
    // Teacher.java
    public class Teacher {
        private String name;
        private int age;
        //...
    }
    
    // StreamMap.java
    public class StreamMap {
        public static void main(String[] args) {
            List<Student> list = new ArrayList<>();
            Student stu1 = new Student("张三", 24);
            Student stu2 = new Student("李四", 22);
            Student stu3 = new Student("王五", 25);
            Collections.addAll(list, stu1, stu2, stu3);
            List<Teacher> teacList = list.stream().map(stu -> {
               String name = stu.getName();
               int age = stu.getAge();
               return new Teacher(name, age);
            }).collect(Collectors.toList());
            teacList.stream().forEach(stu -> System.out.println(stu));
            //Teacher{name='张三', age=24}
            //Teacher{name='李四', age=22}
            //Teacher{name='王五', age=25}
        }
    }
    

      

      

  • 相关阅读:
    安全事件关联分析方法
    网络安全公开数据集
    2019年汽车网络安全
    基于知识图谱的APT组织追踪治理——实践性比较强
    Hutool中常用的工具类和方法
    阿里云短信服务
    Java8实现List转Map
    centos下安装nodejs
    微信小程序,联系客服
    mysql空闲连接
  • 原文地址:https://www.cnblogs.com/xulinjun/p/14804097.html
Copyright © 2011-2022 走看看