jdk8_Stream流使用-映射

map()实现类型转换

接收一个函数作为方法参数,这个函数会被应用到集合中每一个元素上,并最终将其映射为一个新的元素

案例:
将List 转换List

public class MapDemo {

    static class KeyValue {
        private Integer key;
        private String value;

        public KeyValue(Integer key, String value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public String toString() {
            return "KeyValue{" +
                    "key=" + key +
                    ", value='" + value + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student(1, "张三", 23));
        studentList.add(new Student(2, "李四", 20));
        studentList.add(new Student(3, "王五", 19));
        studentList.add(new Student(4, "小明", 21));
        studentList.add(new Student(5, "小红", 24));

        List<KeyValue> collect = studentList.stream()
                .map(item -> new KeyValue(item.getId(), item.getName()))
                .collect(Collectors.toList());

        System.out.println(collect);

        int sum = Arrays.asList("1", "2", "23", "89", "33").stream()
                .mapToInt(item -> Integer.parseInt(item))
                .sum();

        System.out.println(sum);
    }
}

**

运行结果:

[KeyValue{key=1, value='张三'}, KeyValue{key=2, value='李四'}, KeyValue{key=3, value='王五'}, KeyValue{key=4, value='小明'}, KeyValue{key=5, value='小红'}]

map衍生方法

![image.png](https://img-blog.csdnimg.cn/img_convert/1f72a28e7665e7b510960c4d0bdb3927.png#align=left&display=inline&height=256&margin=[object Object]&name=image.png&originHeight=256&originWidth=508&size=33226&status=done&style=none&width=508)

案例:
字符串集合求和

public class MapDemo {

    public static void main(String[] args) {
        int sum = Arrays.asList("1", "2", "23", "89", "33").stream()
                .mapToInt(item -> Integer.parseInt(item))
                .sum();

        System.out.println(sum);
    }
}