user1945064
user1945064

Reputation: 209

Filtering a HashMap based of a list in Java 8

I have a map of map which needs to be filtered based of another array list. Currently i used the implementation running a forEach loop on the list and comparing with the map of map to build another filtered version of the map.

Is there a better solution to this in Java 8?

// this map has all the data
Map<String, Map<String, String>> mapOfMap = new HashMap<>();

// this is the new filtered map that i am trying to build
Map<String, Map<String, String>> filteredMap = new HashMap<>();

listofItems.forEach(item -> {
    Map<String, String> itemIdMap = mapOfMap.get(item.getItemId().toString());
    if (itemIdMap != null) {
        String key = itemIdMap.get(item.getUT());
        if (key != null) {
            // setting the new map
            Map<String, String> newItemMap = filteredMap.get(item.getItemId().toString());
            Map<String, String> filteredUTMap = new HashMap<>();
            if (newItemMap == null) {
                filteredUTMap.put(item.getUT(), key);
                filteredMap.put(item.getItemId().toString(), filteredUTMap);
            } else {
                String newKey = newItemMap.get(item.getUT());
                if (newKey == null) {
                    filteredMap.get(item.getItemId().toString()).put(item.getUT(), key);
                }
            }
        }
    }
});

Upvotes: 0

Views: 860

Answers (1)

alan7678
alan7678

Reputation: 2311

I am not sure what condition you are filtering on. But you might consider using a stream here.

For example.

Map<String, Map<String, String>> originalMap= new HashMap<>();
originalMap.entrySet().stream().filter(this::filterMapEntry).collect(Collectors.toMap(Entry::getKey, Entry::getValue));

boolean filterMapEntry(Entry<String, Map<String, String>> entry) {
      return true;
   }

Upvotes: 2

Related Questions