Yu Wan
Yu Wan

Reputation: 23

How to map a list of string to emptylists?

I have a set of String and want to map each of them to an empty list then return. I know a for loop could solve it, but is there a good way to do it with Java Stream?

e.g: I have a Set of {"a", "b", "c"}

and I want to return a map Map<String, List<Object>> to be something like {"a": emptyList(), "b": emptyList(), "c": emptyList()}

Upvotes: 2

Views: 334

Answers (1)

user11595728
user11595728

Reputation:

You can use Collectors.toMap for this purpose.

Map<String, List<Object>> result = strings.stream()
    .collect(toMap(identity(), e -> new ArrayList<>()));

(where identity() is also statically imported).

Given your question, you may also be interested in Map.computeIfAbsent, which allows you to do the initialization lazily.

Map<String, List<Object>> result = new HashMap<>();
List<Object> listForA = result.computeIfAbsent("a", e -> new ArrayList<>());
// result = {a=[]}

Upvotes: 5

Related Questions