1

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;
}

1 Answer 1

2

Figured out a possible solution myself:

return Stream.of(fruitNames)
             .map(fruitMap::get)
             .filter(Objects::nonNull)
             .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

Might wanna use Objects.nonNull. A good alternative to have clean lambda code.

Your Answer

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.