Create a map from a list of strings (strings) with streams
I have List
from String
(s) but I want to convert it to Map<String, Boolean>
from List<String>
making all mappings boolean
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 thread usage?
source to share
Yes. You can also use Arrays.asList(T...)
to create List
. Then use Stream
to collect 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 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);
What are the outputs
{=false, cd=true, bc=true, ab=true}
source to share
The shortest way I can think of is not a one-liner, but it's really short:
Map<String, Boolean> map = new HashMap<>();
list.forEach(k -> map.put(k, true));
This is a personal taste, but I only use streams when I need to apply transforms to the source or filter out some elements, etc.
As @ holi-java pointed out in the comments, many times using the values Map
with is Boolean
pointless as there are only two possible values ββfor key matching. Instead, Set
you can use it to solve pretty much all of the same problems that you would use Map<T, Boolean>
.
source to share
If you are going to modify an existing one Map<..., Boolean>
, you can use Collections.newSetFromMap
. It allows you to consider such a map as Set
:
Collections.newSetFromMap(alphaToBoolMap).addAll(list);
source to share