HashMap Stream and Filtering Example

HashMap can be filtered with the filter() method of the Java Stream API.

HashMap Stream and Filtering Example

package com.javaguides.collections.hashmapexamples;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class IterateOverHashMap {
    public static void main(String[] args) {
       Map<String, String> countryISOCodeMapping = new HashMap<>();

          countryISOCodeMapping.put("India", "IN");
          countryISOCodeMapping.put("United States of America", "US");
          countryISOCodeMapping.put("Russia", "RU");
          countryISOCodeMapping.put("Japan", "JP");
          countryISOCodeMapping.put("China", "CN");

        Map<String, String> filteredCapitals = countryISOCodeMapping.entrySet().stream()
                .filter(map ->  map.getValue().length() == 2)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        
        filteredCapitals.entrySet().forEach(System.out::println);      
    }
}

Output

China=CN
Japan=JP
United States of America=US
Russia=RU
India=IN

Related HashMap Source Code Examples


Comments