我有一个 List
的 String
(s),但我想将其转换为 Map<String, Boolean>
来自 List<String>
, 使得所有的 boolean
映射设置为 true。我有以下代码。
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}
}
}
有没有办法使用流来减少这种情况?
最佳答案
是的。您也可以使用 Arrays.asList(T...)
创建您的 List
。然后使用 Stream
到 collect这与 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);
输出
{cd=true, bc=true, ab=true}
为了完整起见,我们还应考虑一个示例,其中某些值应为 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);
哪些输出
{=false, cd=true, bc=true, ab=true}
关于java - 使用流从字符串列表创建映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44981932/