一、map转list的定义及作用
map转list可以称呼为map的扁平化(flatMap)处理,可以将一个map结构的数据转换为一个list结构的数据。通常在Java8的函数式编程中,经常需要将map转换成list的数据结构。
在实际开发中,经常需要对map进行操作,如map的遍历、map的排序等等。数字集合List是我们在开发中使用较多的数据结构之一。map转list则可以让我们更加方便的对map进行操作。
二、map转list的实现方式
Java8中提供的Stream API可以方便我们对map进行转换操作。我们可以通过以下两种方式实现转换:
1. 使用流的map方法实现map转list
Map map = new HashMap<>();
map.put(1, "apple");
map.put(2, "orange");
map.put(3, "pear");
List list = map.entrySet().stream()
.map(e -> e.getValue())
.collect(Collectors.toList());
上面代码中,使用entrySet()将map的键值对转换为Set类型,然后通过流的map方法将键值对中的value取出,最后通过collect方法将流收集为一个List类型的集合。
2. 使用Stream的flatmap方法实现map转list
Map> map = new HashMap<>();
map.put(1, Arrays.asList("apple", "boy"));
map.put(2, Arrays.asList("cat", "dog", "elephant"));
map.put(3, Arrays.asList("fish

661

被折叠的 条评论
为什么被折叠?



