I want to create a new List from Map from existing list.
I got an ArrayList as below structure;
ArrayList
0 = {LinkedHashMap}
0 = {LinkedHashMapEntry} "name" --> "value"
1 = {LinkedHashMapEntry} "surname" --> "value"
1 = {LinkedHashMap}
0 = {LinkedHashMapEntry} "name" --> "value"
1 = {LinkedHashMapEntry} "surname" --> "value"
....
What I want to do is get all name values as a new list.
List<String> allNames = ....
Is there any way to get this list with using Java Stream?
asked Feb 8, 2018 at 8:08
1 Answer 1
Yes:
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
answered Feb 8, 2018 at 8:11
-
Can you please explain this? I was trying something similar on my IDE but didn't get this .map(m-> m.get("name")) thing. As the list is of Map, won't it pass a map as "m" ?Bilbo Baggins– Bilbo Baggins2018年02月08日 08:13:08 +00:00Commented Feb 8, 2018 at 8:13
-
@BilboBaggins see edit. Yes,
m
's type isMap
(orLinkedHashMap
, depending on how you declared the inputList
)Eran– Eran2018年02月08日 08:16:56 +00:00Commented Feb 8, 2018 at 8:16 -
A side note :
filter(Objects::nonNull)
is not a requirement.davidxxx– davidxxx2018年02月08日 08:19:02 +00:00Commented Feb 8, 2018 at 8:19 -
@davidxxx It made sense to me to avoid having
null
s in the outputList
.Eran– Eran2018年02月08日 08:20:10 +00:00Commented Feb 8, 2018 at 8:20
lang-java