比较HashMap <string,double =“”>和List <arraylist <string>&gt;在Java中

时间:2016-03-03 01:09:40

标签: java arraylist hashmap

我有一个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))) {

但是,不行。怎么做?

2 个答案:

答案 0 :(得分:3)

使用stream 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)

答案 1 :(得分:1)

你走了:

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);
相关问题