2

I have a Data structure - ArrayList> and this is what I need to do -

ArrayList<HashMap<String, String>> optMapList;
//populated optMapList with some code. Not to worry abt this

List<String> values = new ArrayList<String>();

for(HashMap<String,String> entry: optMapList){
    values.add(entry.get("optValue"));
}

How do we use Java Streams to achieve the same objective?

Shirish Herwade
  • 11,461
  • 20
  • 72
  • 111
Prateek Narendra
  • 1,837
  • 5
  • 38
  • 67

1 Answers1

5
 optMapList.stream()
           .filter(Objects:nonNull) // potentially filter null maps
           .map(m -> m.get("optValue"))
           .filter(Objects::nonNull) // potentially filter null values form the map 
           // .collect(Collectors.toCollection(ArrayList::new)) 
           .collect(Collectors.toList())
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Utilise toCollection to guarantee the type of List returned. – Ousmane D. Apr 06 '18 at 08:26
  • @Aominè that is actually a very good point btw, there was comment from Stuart Marks that are thinking into changing `toList` so that it returns an immutable List, just like `toUnmodifiableList` in jdk-10... – Eugene Apr 06 '18 at 08:29
  • Shouldn't `filter` be before `map`? – lexicore Apr 06 '18 at 08:31
  • @lexicore I *know*, thus the potentially word in there... I like your meticulosity today ;) – Eugene Apr 06 '18 at 08:43
  • @Eugene you should remove the second filter that is not required (what Lexicore refered as he said "move") – davidxxx Apr 06 '18 at 08:44
  • @davidxxx thus the comment `potentially` again, required or not is for OP to decide – Eugene Apr 06 '18 at 08:45
  • According to the actual code it is not required but as you wish. – davidxxx Apr 06 '18 at 08:47
  • @davidxxx if only we would always treat all questions literally... but point noted, thx – Eugene Apr 06 '18 at 08:48
  • 2
    Inserting spurious `null` checks creates more harm than good. The original code suggests that the OP assumes that the maps are never `null`, so the code should fail loudly when this assumption does not hold, instead of skipping entries silently. In case of the values, we don’t know whether they are supposed to be always present and non-`null` or whether potentially having `null` entries in the result list is intended. In either case, the original code guarantees that the source list positions match the result list positions and inserting filters destroys this invariant. – Holger Apr 06 '18 at 09:58