列出值时获取哈希图的键

Get the key of an hashmap when the values are list

我有一个订单列表(订单 ID)List<Integer>order,其中包含整数值。 我还有一个 <String, List<Integer>> 形式的 Hashmap,其中包含客户名称作为键,每个订单列表作为值。

我想做的是从我的第一个订单列表中获取值并查看它属于哪个客户。结果将是已下订单的客户列表。

例如:

     if we have an first list of orders :  
     order = [1,2,3,4,5,6,7] 
     and after we have  
     hashmap={alice =[1,2,3], bob=[4,5,6], paul=[10,11]} 

输出应该是
List<String> res = [alice, bob] 因为“paul”命令不在第一个列表中。

如果有人能帮助我,那就太好了。

您可以使用另一个HashMap,并使用订单id作为键。

    Map<Integer, String> orderNameMapping = new HashMap<>();
    Set<String> keySet = hashmap.keySet();
    for(String key: keySet){
        List<Integer> orderIds = hashmap.get(key);
        for(Integer orderId : orderIds) {
            orderNameMapping.put(orderId, key);
        }
    }

    List<String> res = orders.stream().map(orderNameMapping::get).collect(Collectors.toList());

流过您的地图条目,过滤具有与您的订单列表元素匹配的值的条目,映射到键并收集到列表:

List<String> res = hashmap.entrySet().stream()
                          .filter(e -> e.getValue().stream().anyMatch(order::contains))
                          .map(Map.Entry::getKey)
                          .collect(Collectors.toList());

看到这个code run live at Ideone.com

所以伪代码应该是这样的。

  • 创建一个字符串列表,以return结果。
  • l1:遍历 customer/orders
  • 的 hashmap
  • ...遍历订单。
  • ......在顺序数组中搜索顺序。如果没有找到,继续 l1
  • ...至此,所有的订单都找到了。将客户添加到 return 列表。
  • return 列表。

希望对您有所帮助。