我有var value = Phonic['tiger']
List
(s),但我希望将其转换为String
中的Map<String, Boolean>
,使所有List<String>
成为boolean
} mappings设置为 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}
}
}
有没有办法使用流来减少这种情况?
答案 0 :(得分:7)
是。您也可以使用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}
答案 1 :(得分:6)
我能想到的最短路线不是单线,但确实很短:
Map<String, Boolean> map = new HashMap<>();
list.forEach(k -> map.put(k, true));
这是个人品味,但我只在需要将转换应用于源,或过滤掉某些元素等时才使用流。
正如@ holi-java的评论中所建议的那样,多次使用Map
Boolean
值是没有意义的,因为只有两个可能的值来映射键。相反,Set
可用于解决您使用Map<T, Boolean>
解决的几乎所有相同问题。
答案 2 :(得分:0)
如果您要改变现有的Map<..., Boolean>
,可以使用Collections.newSetFromMap
。它可以让您将此类地图视为Set
:
Collections.newSetFromMap(alphaToBoolMap).addAll(list);