[英]Compare HashMap<String, Double> and List<ArrayList<String>> in Java
我有一个HashMap<String, Double>
像arr1[]-{AA=0.05, BB=0.031, CC=0.056}
和List<ArrayList<String>>
像arr2[]-[ [AA,BB,CC] , [BB, CC] , [AA, CC]].
我想获取类似List<ArrayList<Double>>
输出。它将是[ [0.05,0.031,0.056] , [0.031, 0.056] , [0.05, 0.056]].
我用了 ,
for (int i = 0; i < arr2.size(); i++) {
if (arr1.containsKey(arr2.get(i))) {
但是,不起作用。 怎么做?
使用流API可以轻松实现:
lists.stream()
.map(list -> list.stream().map(map::get).collect(Collectors.toCollection(ArrayList::new))
.collect(Collectors.toList());
假设lists
这里是你List<ArrayList<String>>
和map
是你HashMap<String, Double>
,将返回List<ArrayList<Double>>
您期望。
我想补充一点,我不知道为什么要在列表中使用ArrayList
,但是如果没有特殊原因,请使用Collectors.toList()
而不是Collectors.toCollection(ArrayList::new)
。
干得好:
Map<String, Double> mappings = //get mappings
List<ArrayList<String>> source = //get source
List<ArrayList<Double>> target = new ArrayList<>();
for(ArrayList<String> sourceElement : source){
ArrayList<Double> targetElememt = new ArrayList<>();
for(String sourceElementString : sourceElement){
targetElememt.add(mappings.get(sourceElementString));
}
target.add(targetElememt);
}
System.out.println(target);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.