我想从现有列表中的Map创建一个新列表。
我得到一个如下结构的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 Stream获取此列表?
答案 0 :(得分:6)
是:
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