使用流创建一个包含字符串列表的映射

Use*_*yen 5 java hashmap data-structures java-8 java-stream

我有一个ListString(一个或多个),但我想它转换成一个Map<String, Boolean>List<String>,使所有的boolean设置映射真实.我有以下代码.

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}
  }
} 
Run Code Online (Sandbox Code Playgroud)

有没有办法减少使用流?

Ell*_*sch 7

是.你也可以Arrays.asList(T...)用来创建你的List.然后使用a Stream收集这个Boolean.TRUE

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);
Run Code Online (Sandbox Code Playgroud)

输出

{cd=true, bc=true, ab=true}
Run Code Online (Sandbox Code Playgroud)

为了完整起见,我们还应该考虑一些值应该是的例子false.也许是空键

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);
Run Code Online (Sandbox Code Playgroud)

哪个输出

{=false, cd=true, bc=true, ab=true}
Run Code Online (Sandbox Code Playgroud)


Fed*_*ner 6

我能想到的最短路线不是单线,但确实很短:

Map<String, Boolean> map = new HashMap<>();
list.forEach(k -> map.put(k, true));
Run Code Online (Sandbox Code Playgroud)

这是个人品味,但我只在需要将变换应​​用于源,或过滤掉某些元素等时才使用流.


正如@ holi-java的评论中所建议的那样,多次使用Mapwith Boolean值是没有意义的,因为映射键只有两个可能的值.相反,a Set可以用来解决你用a解决的几乎所有相同的问题Map<T, Boolean>.