目录
1 概述
2 map与flatMap
3 常用写法
1 概述
Java8中一些新特性在平时工作中经常会用到,但有时候总感觉不是很熟练,今天特意将这个Java8中的映射记录一下。
2 map与flatMap
map---对集合中的元素逐个进行函数操作映射成另外一个
flatMap---接收一个函数作为参数,将流中的每个值都转换为另一个流,然后把所有的流都连接成一个流。
map举例1:将对象中的元素进行函数操作后提取
@Testpublic void test(){List<Employee> employees = Arrays.asList(new Employee(1, "张三", 23, "郑州", "合法"),new Employee(2, "李四", 24, "合肥", "合法"),new Employee(3, "王五", 25, "青岛", "合法"),new Employee(4, "王二麻子", 26, "上海", "合法"),new Employee(5, "赵子龙", 27, "北京", "合法"));//将集合中的每一个元素取出放入函数中进行操作,比如:将年龄提取出来并且每一个人的年龄都减1List<Integer> collect = employees.stream().map(employee -> employee.getAge() - 1).collect(Collectors.toList());System.out.println(collect);}
map举例2:对集合中的元素直接进行转换
@Testpublic void test(){List<String> stringList = Arrays.asList("aaa", "bbb", "ccc", "ddd");List<String> collect1 = stringList.stream().map(String::toUpperCase).collect(Collectors.toList());System.out.println(collect1);}
map用法:就是将一个函数传入map中,然后利用传入的这个函数对集合中的每个元素进行处理,并且将处理后的结果返回。
需求1:对于给定的单词列表["Hello","World"],你想返回列表["H","e","l","o","W","r","d"]
先用map操作看是否成功:
@Testpublic void test(){List<String> stringList = Arrays.asList("hello", "world");List<String[]> collect = stringList.stream().map(str -> str.split("")).distinct().collect(Collectors.toList());collect.forEach(col-> System.out.println(Arrays.toString(col)));}
大家可以看到返回结果是 两个数组,并没有达到我们的要求。map的操作只是将元素放入map中的函数中使其返回另一个Stream<String[]>类型的,但我们真正想要的是一个Stream[String]类型的,所以我们需要扁平化处理,将多个数组放入一个数组中
看下flatMap的操作:
@Testpublic void test(){List<String> stringList = Arrays.asList("hello", "world");List<String> collect = stringList.stream().map(str -> str.split("")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());System.out.println(collect);}
flatmap用法:使用flatMap的效果是,各个数组并不是分别映射一个流,而是映射成流的内容,所有使用flatMap(Arrays::stream)时生成的单个流被合并起来,扁平化成了一个流。
3 常用写法
将对象中的某一属性放入list中并收集起来
@Testpublic void test(){List<Employee> employees = Arrays.asList(new Employee(1, "张三", 23, "郑州", "合法"),new Employee(2, "李四", 25, "合肥", "合法"),new Employee(3, "王五", 26, "青岛", "合法"),new Employee(4, "王二麻子", 27, "上海", "合法"),new Employee(5, "赵子龙", 28, "北京", "合法"));List<List<String>> collect = employees.stream().map(employee -> {List<String> list = new ArrayList<>();list.add(employee.getName());return list;}).collect(Collectors.toList());System.out.println(collect);
想要了解更多编程小知识,快来关注公众号:爪哇开发吧!每周会不定时的进行更新。