我有一个 customerIds 列表,例如 [12、10、15、18]。它也可以是任何其他数字,也可以是任何顺序。
我有对象列表(List customObjects),其中每个对象在第 0 个位置包含 customerId,在第一个位置包含客户名称。
customObjects[0] ---> Object[0] contains 10 as customer id and scott as customer name
customObjects[1] ---> Object[0] contains 12 as customer id and Mark as customer name
customObjects[2] ---> Object[0] contains 18 as customer id and Brian as customer name
customObjects[3] ---> Object[0] contains 15 as customer id and Pat as customer name
现在我想构建一个地图,在其中我以与 customerIds 列表相同的顺序获取值
预期结果图[12=>Mark, 10=>scott, 15=>Pat, 18=>Brian
我的解决方案(但未优化)
我知道我可以用下面的简单算法实现它,但我正在寻找更优化的解决方案。(我们可以用比较器实现它吗?虽然我不这么认为)
public static void main(String[] args) {
List <Integer> custIds= Arrays.asList(12 , 10, 15, 18);
List <Object []> custObjects= new ArrayList<Object[]>();
Object [] custObject1 ={10,"Scott"};
Object [] custObject2 ={12,"Mark"};
Object [] custObject3 ={18,"Brian"};
Object [] custObject4 ={15,"Pat"};
custObjects.add(custObject1);
custObjects.add(custObject2);
custObjects.add(custObject3);
custObjects.add(custObject4);
Map custMap= new LinkedHashMap();
for(Integer custId : custIds){
for(Object [] custObject:custObjects){
if(custObject[0]==custId){
custMap.put(custObject[0], custObject[1]);
break;
}
}
}
System.out.println("map is"+custMap);
}
我正在寻找优化的解决方案(类似于我提出的解决方案或完全不同的解决方案),我可以在其中保存循环迭代。另一种解决方案是,首先我准备哈希图,键为 custObject[0],值为 custObject[1]。然后在我想要排序的列表上运行一个循环,从 hashmap 中获取值并将其放入linkedhashmap。