Search code examples
javalistjava-stream

Retrieve values from a list of maps using streams


I have a list of maps: List<Map<String, Object>>

The maps consist of the keys name and position.

I need to retrieve all values of the key position from all maps of the list.

Currently I have this:

public List<String> getPositions() {
    List<String> positions = new ArrayList<>();
    list.forEach( map -> {
        for ( Entry<String, Object> entry : map.entrySet() )
            if ( entry.getKey().toString().equals( "position" ) )
                positions.add( entry.getValue().toString() );
    } );
    return positions;
}

Is it possible to do this faster with Java Stream?


Solution

  • As far as I understand your question, I suppose the list has the following structure:

    List<Map<String, Object>> listOfMap = new ArrayList<>();
    

    And any number these Maps in the list can possibly have a key "position" which you want to use to extract the value. Use:

    List<String> positions = listOfMap.stream()                         // Stream
                                      .map(map -> map.get("position"))  // Get from map a value by key
                                      .collect(Collectors.toList());    // Collect to List
    

    I would like to add up that Stream-API is definitely not a substitution of for-loops like you have provided in the snippet. As its documentation states, it should be non-infering and stateless. So, replacing a for-loop adding an element elsewhere using Stream is not a good idea - you have to find another way.