转载 

Java 8 – Filter a Map examples

分类:    206人阅读    IT小君  2018-07-01 09:41

Few Java examples to show you how to filter a Map with Java 8 stream API.

Before Java 8 :


	Map<Integer, String> map = new HashMap<>();
    map.put(1, "linode.com");
    map.put(2, "heroku.com");
		
	String result = "";
	for (Map.Entry<Integer, String> entry : map.entrySet()) {
		if("something".equals(entry.getValue())){
			result = entry.getValue();
		}
	}

With Java 8, you can convert a Map.entrySet() into a stream, follow by a filter() and collect() it.


	Map<Integer, String> map = new HashMap<>();
    map.put(1, "linode.com");
    map.put(2, "heroku.com");
	
	//Map -> Stream -> Filter -> String
	String result = map.entrySet().stream()
		.filter(x -> "something".equals(x.getValue()))
		.map(x->x.getValue())
		.collect(Collectors.joining());

	//Map -> Stream -> Filter -> MAP
	Map<Integer, String> collect = map.entrySet().stream()
		.filter(x -> x.getKey() == 2)
		.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
		
	// or like this
	Map<Integer, String> collect = map.entrySet().stream()
		.filter(x -> x.getKey() == 3)
		.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
		

1. Java 8 – Filter a Map

A full example to filter a Map by values and return a String.

TestMapFilter.java

package com.mkyong;

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

public class TestMapFilter {

    public static void main(String[] args) {

        Map<Integer, String> HOSTING = new HashMap<>();
        HOSTING.put(1, "linode.com");
        HOSTING.put(2, "heroku.com");
        HOSTING.put(3, "digitalocean.com");
        HOSTING.put(4, "aws.amazon.com");

        // Before Java 8
        String result = "";
        for (Map.Entry<Integer, String> entry : HOSTING.entrySet()) {
            if ("aws.amazon.com".equals(entry.getValue())) {
                result = entry.getValue();
            }
        }
        System.out.println("Before Java 8 : " + result);

        //Map -> Stream -> Filter -> String
        result = HOSTING.entrySet().stream()
                .filter(map -> "aws.amazon.com".equals(map.getValue()))
                .map(map -> map.getValue())
                .collect(Collectors.joining());

        System.out.println("With Java 8 : " + result);

        // filter more values
        result = HOSTING.entrySet().stream()
                .filter(x -> {
                    if (!x.getValue().contains("amazon") && !x.getValue().contains("digital")) {
                        return true;
                    }
                    return false;
                })
                .map(map -> map.getValue())
                .collect(Collectors.joining(","));

        System.out.println("With Java 8 : " + result);

    }

}

Output


Before Java 8 : aws.amazon.com
With Java 8 : aws.amazon.com
With Java 8 : linode.com,heroku.com

2. Java 8 – Filter a Map #2

Yet another example to filter a Map by key, but this time will return a Map

TestMapFilter2.java

package com.mkyong;

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

public class TestMapFilter2 {

    public static void main(String[] args) {

        Map<Integer, String> HOSTING = new HashMap<>();
        HOSTING.put(1, "linode.com");
        HOSTING.put(2, "heroku.com");
        HOSTING.put(3, "digitalocean.com");
        HOSTING.put(4, "aws.amazon.com");

        //Map -> Stream -> Filter -> Map
        Map<Integer, String> collect = HOSTING.entrySet().stream()
                .filter(map -> map.getKey() == 2)
                .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

        System.out.println(collect); //output : {2=heroku.com}

        Map<Integer, String> collect2 = HOSTING.entrySet().stream()
                .filter(map -> map.getKey() <= 3)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println(collect2); //output : {1=linode.com, 2=heroku.com, 3=digitalocean.com}

    }

}

Output


{2=heroku.com}
{1=linode.com, 2=heroku.com, 3=digitalocean.com}

3. Java 8 - Filter a Map #3 - Predicate

This time, try the new Java 8 Predicate

TestMapFilter3.java

package com.mkyong;

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

public class TestMapFilter3 {

	// Generic Map filterbyvalue, with predicate
    public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {
        return map.entrySet()
                .stream()
                .filter(x -> predicate.test(x.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    public static void main(String[] args) {

        Map<Integer, String> HOSTING = new HashMap<>();
        HOSTING.put(1, "linode.com");
        HOSTING.put(2, "heroku.com");
        HOSTING.put(3, "digitalocean.com");
        HOSTING.put(4, "aws.amazon.com");
        HOSTING.put(5, "aws2.amazon.com");

        //  {1=linode.com}
        Map<Integer, String> filteredMap = filterByValue(HOSTING, x -> x.contains("linode"));
        System.out.println(filteredMap);

        // {1=linode.com, 4=aws.amazon.com, 5=aws2.amazon.com}
        Map<Integer, String> filteredMap2 = filterByValue(HOSTING, x -> (x.contains("aws") || x.contains("linode")));
        System.out.println(filteredMap2);

        // {4=aws.amazon.com}
        Map<Integer, String> filteredMap3 = filterByValue(HOSTING, x -> (x.contains("aws") && !x.contains("aws2")));
        System.out.println(filteredMap3);

        // {1=linode.com, 2=heroku.com}
        Map<Integer, String> filteredMap4 = filterByValue(HOSTING, x -> (x.length() <= 10));
        System.out.println(filteredMap4);

    }

}

Output


{1=linode.com}
{1=linode.com, 4=aws.amazon.com, 5=aws2.amazon.com}
{4=aws.amazon.com}
{1=linode.com, 2=heroku.com}

References

  1. Processing Data with Java SE 8 Streams
  2. Java Collectors JavaDoc
  3. Java 8 Streams filter examples
点击广告,支持我们为你提供更好的服务

html5 canvas彩色碎片组合球形旋转动画特效

js+css3抽奖转盘旋转点餐代码

有机水果蔬菜HTML5网站模板

网页设计开发公司网站模板

canvas炫酷鼠标移动文字粒子特效

中小型创意设计服务公司网站模板

css鼠标跟随文字模糊特效

css+js实现的颜色渐变数字时钟动画特效

现代时尚家具公司网站模板

响应式时尚单品在线商城网站模板

html5 canvas进度条圆环图表统计动画特效

HTML5 Canvas竖直流动线条背景动画特效

响应式太阳能能源公司网站模板

响应式咖啡饮品宣传网站模板

小众时尚单品在线电子商务网站模板

html5 svg夜空中星星流星动画场景特效

HTML5现代家居装潢公司网站模板

jQuery右端悬浮带返回顶部特效

HTML5数字产品服务公司网站模板

html5图标下拉搜索框自动匹配代码

点击广告,支持我们为你提供更好的服务
 工具推荐 更多»
点击广告,支持我们为你提供更好的服务