Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Map out of a List of String(s) with streams

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?

like image 347
User_Targaryen Avatar asked Jul 08 '17 02:07

User_Targaryen


People also ask

How do you make a string map?

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.

Can we create map with List in Java?

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.

Can we use streams for 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.


1 Answers

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}
like image 168
Elliott Frisch Avatar answered Sep 19 '22 21:09

Elliott Frisch