Home > Blockchain >  Get the key of an hashmap when the values are list
Get the key of an hashmap when the values are list

Time:05-16

I have a list of orders(order id) List<Integer>order with Integer values in it. I also have a Hashmap of the form <String, List<Integer>> which contains the customer names as keys and for each one a list of orders as values.

What I would like to do is take the values from my first order list and see which customer it belongs to. The result will be a list of customers who have made an order.

For example :

     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]} 

the output should be
List<String> res = [alice, bob] because "paul" commands are not in the first list.

If someone coud help me for this it would be nice.

CodePudding user response:

Stream over your map entries, filter entries having values having any match with elements of your order list, map to key and collect to list:

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

See this code run live at Ideone.com.

CodePudding user response:

You can use another HashMap and use the order id as the key.

    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());

CodePudding user response:

So the pseudocode would be something like.

  • Create a string list, to return the result.
  • l1: Loop though the hashmap of customer/orders
  • ...loop through the orders.
  • ......search for the order in the orderarray. If not found, continue l1
  • ...at this point, all orders have been found. Add customer to return list.
  • return the list.

hope this helps.

  • Related