2

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

6

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
4
  • 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" ? Commented Feb 8, 2018 at 8:13
  • @BilboBaggins see edit. Yes, m's type is Map (or LinkedHashMap, depending on how you declared the input List) Commented Feb 8, 2018 at 8:16
  • A side note : filter(Objects::nonNull) is not a requirement. Commented Feb 8, 2018 at 8:19
  • @davidxxx It made sense to me to avoid having nulls in the output List. Commented Feb 8, 2018 at 8:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.