我有一个 HashMap,其中包含各种“产品”作为键和“产品组 ID”作为值。
我需要分离出具有相同组 ID 的产品,并将它们放入一个新的 ArrayList 中(仅包含产品,即键)。
我对如何做到这一点感到困惑,我们将不胜感激!
是这样的:
HashMap: (1,a) (2,b) (3,c) (4,a) (5,b)
新的 ArrayList 应该包含:{1,4} - 这个列表被发送到另一个函数进行处理。
同样,2,5 应该存储在另一个列表中并进行处理。
最后 3 应该存储在数组列表中并进行处理。
您可以这样做的一种方法是使用 ArrayLists
的另一个 HashMap
,然后向其添加值。你可以试试下面的代码:
我假设 Product 是一个字符串,ID 是一个整数,但您可以更改它。
Map < Integer, String > sourceMap = Map.of ( 1 , "a" , 2 , "b" , 3 , "c" , 4 , "a " , 5 , "b" );
HashMap <String, ArrayList<Integer>> result = new HashMap<>();
for (Map.Entry <Integer, String> entry : sourceMap.entrySet()) {
String value = entry.getValue();
int key = entry.getKey();
if (result.containsKey(value)) {
ArrayList<Integer>temp = result.get(value);
temp.add(key);
} else {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(key);
result.put(value, temp);
}
}
System.out.println ("result.toString():\n" + result);
现在,您有一个名为 result
的 HashMap
,其中包含您想要的 ArrayList
。您可以遍历以获取每个单独的 ArrayList
。