ViV
ViV

Reputation: 317

java 8 streams copy specific objects from map to list

Looking for alternative code in Java8/streams.
I want to copy specific values from a Map into a List using a predefined array of Keys.

The code to accomplish this task in Java 7 is as follows:

public List<Fruit> getFruitList(Map<String, Fruit> fruitMap) {
    final String[] fruitNames = { "apple", "banana", "mango" };
    final ArrayList<Fruit> fruitList = new ArrayList<>(fruitNames.length);
    for (int i = 0; i < fruitNames.length; i++) {
        final String fruitName = fruitNames[i];
        final Fruit fruit = fruitMap.get(fruitName);
        if (fruit != null) {
            fruitList.add(fruit);
        }
    }
    fruitList.trimToSize();
    return fruitList;
}

Upvotes: 1

Views: 332

Answers (1)

ViV
ViV

Reputation: 317

Figured out a possible solution myself:

return Stream.of(fruitNames)
             .map(fruitMap::get)
             .filter(Objects::nonNull)
             .collect(Collectors.toList());

Upvotes: 2

Related Questions