使用来自现有列表的 HashMap 的值创建一个新列表
Create a new list with values from HashMap from existing list
我想从现有列表的地图创建一个新列表。
我得到了一个结构如下的 ArrayList;
ArrayList
0 = {LinkedHashMap}
0 = {LinkedHashMapEntry} "name" --> "value"
1 = {LinkedHashMapEntry} "surname" --> "value"
1 = {LinkedHashMap}
0 = {LinkedHashMapEntry} "name" --> "value"
1 = {LinkedHashMapEntry} "surname" --> "value"
....
我想要做的是将所有名称值作为一个新列表获取。
List<String> allNames = ....
有什么方法可以使用 Java 流来获取此列表?
是:
List<String> allNames =
list.stream() // this creates a Stream<LinkedHashMap<String,String>>
.map(m->m.get("name")) // this maps the original Stream to a Stream<String>
// where each Map of the original Stream in mapped to the
// value of the "name" key in that Map
.filter(Objects::nonNull) // this filters out any null values
.collect(Collectors.toList()); // this collects the elements
// of the Stream to a List
我想从现有列表的地图创建一个新列表。
我得到了一个结构如下的 ArrayList;
ArrayList
0 = {LinkedHashMap}
0 = {LinkedHashMapEntry} "name" --> "value"
1 = {LinkedHashMapEntry} "surname" --> "value"
1 = {LinkedHashMap}
0 = {LinkedHashMapEntry} "name" --> "value"
1 = {LinkedHashMapEntry} "surname" --> "value"
....
我想要做的是将所有名称值作为一个新列表获取。
List<String> allNames = ....
有什么方法可以使用 Java 流来获取此列表?
是:
List<String> allNames =
list.stream() // this creates a Stream<LinkedHashMap<String,String>>
.map(m->m.get("name")) // this maps the original Stream to a Stream<String>
// where each Map of the original Stream in mapped to the
// value of the "name" key in that Map
.filter(Objects::nonNull) // this filters out any null values
.collect(Collectors.toList()); // this collects the elements
// of the Stream to a List