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衍生方法

案例:
字符串集合求和
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);
}
}