我有一个哈希图,其中包含各种"产品"作为键和"产品组ID"作为值。我需要分离出具有相同组ID的产品,并将它们放在新的ArrayList中(仅产品,即键(。我被困在如何做到这一点,任何帮助将不胜感激!
像这样:哈希图: (1,a( (2,b( (3,c( (4,a( (5,b(新的 ArrayList 应包含:{1,4} - 此列表被发送到另一个函数进行处理。同样,2,5 应该存储在另一个列表中并进行处理。最后 3 应该存储在数组列表中并进行处理。
一种方法是再HashMap
ArrayLists
,然后向其添加值。您可以尝试以下代码:
我假设产品是一个字符串,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
。
我推荐以下模式。
假设您有一个简单的HashMap<String, String>
。然后你可以这样做:
Map<String, List<String>> result = map.entrySet().stream().collect(
Collectors.groupingBy(e -> e.getValue(),
Collectors.mapping(e -> e.getKey(), Collectors.toList()))
)
结果是:{a=[1, 4], b=[2, 5], c=[3]}
这些列表可以简单地通过result.get("a")
等访问。
我认为你需要这样的东西:
private static Map<Product, Long> map = new HashMap<>();
public static void main(String[] args) {
fillTestData();
List<Product> products = findProductByGroup(1L);
System.out.println(products.size());
}
private static List<Product> findProductByGroup(Long groupId){
return map.entrySet().stream()
.filter(entry -> entry.getValue() == groupId)
.map(Entry::getKey)
.collect(Collectors.toList());
}
private static void fillTestData() {
String product = "product";
long groupId = 0;
for(int i = 0; i < 100; i++) {
if(i % 2 == 0) {
groupId = 1;
}else {
groupId = 2;
}
map.put(new Product(product+i), groupId);
}
}
其他你已经清楚地声明你需要什么