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?
Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name becomes the value of the HashMap object. In order to convert strings to HashMap, the process is divided into two parts: The input string is converted to an array of strings as output.
The Map class's object contains key and value pairs. You can convert it into two list objects one which contains key values and the one which contains map values separately. Create a Map object. Create an ArrayList of integer type to hold the keys of the map.
Stream is an interface and T is the type of stream elements. mapper is a stateless function which is applied to each element and the function returns the new stream. Example 1 : Stream map() function with operation of number * 3 on each element of stream. // given function to this stream.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With