Reputation: 4225
I have a List
of String
(s), but I want to convert it into a Map<String, Boolean>
from the List<String>
, making all of the boolean
mappings set to true. I have the following code.
import java.lang.*;
import java.util.*;
class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("ab");
list.add("bc");
list.add("cd");
Map<String, Boolean> alphaToBoolMap = new HashMap<>();
for (String item: list) {
alphaToBoolMap.put(item, true);
}
//System.out.println(list); [ab, bc, cd]
//System.out.println(alphaToBoolMap); {ab=true, bc=true, cd=true}
}
}
Is there a way to reduce this using streams?
Upvotes: 8
Views: 7106
Reputation: 28133
If you are going to mutate an existing Map<..., Boolean>
, you can use Collections.newSetFromMap
. It lets you treat such a map as a Set
:
Collections.newSetFromMap(alphaToBoolMap).addAll(list);
Upvotes: 0
Reputation: 34450
The shortest way I can think of is not a one-liner, but it's indeed short:
Map<String, Boolean> map = new HashMap<>();
list.forEach(k -> map.put(k, true));
This is personal taste, but I only use streams when I need to apply transformations to the source, or filter out some elements, etc.
As suggested in the comments by @holi-java, many times, using a Map
with Boolean
values is pointless, since there are only two possible values to map keys to. Instead, a Set
could be used to solve almost all the same problems you'd solve with a Map<T, Boolean>
.
Upvotes: 8
Reputation: 201409
Yes. You can also use Arrays.asList(T...)
to create your List
. Then use a Stream
to collect this with Boolean.TRUE
like
List<String> list = Arrays.asList("ab", "bc", "cd");
Map<String, Boolean> alphaToBoolMap = list.stream()
.collect(Collectors.toMap(Function.identity(), (a) -> Boolean.TRUE));
System.out.println(alphaToBoolMap);
Outputs
{cd=true, bc=true, ab=true}
For the sake of completeness, we should also consider an example where some values should be false
. Maybe an empty key like
List<String> list = Arrays.asList("ab", "bc", "cd", "");
Map<String, Boolean> alphaToBoolMap = list.stream().collect(Collectors //
.toMap(Function.identity(), (a) -> {
return !(a == null || a.isEmpty());
}));
System.out.println(alphaToBoolMap);
Which outputs
{=false, cd=true, bc=true, ab=true}
Upvotes: 11