Java 8 – Filter a Map examples
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}
http://www.mkyong.com/java8/java-8-filter-a-map-examples/

Java 8 – Filter a Map examples的更多相关文章

  1. react+redux教程(三)reduce()、filter()、map()、some()、every()、...展开属性

    reduce().filter().map().some().every()....展开属性   这些概念属于es5.es6中的语法,跟react+redux并没有什么联系,我们直接在https:// ...

  2. Java集合框架之map

    Java集合框架之map. Map的主要实现类有HashMap,LinkedHashMap,TreeMap,等等.具体可参阅API文档. 其中HashMap是无序排序. LinkedHashMap是自 ...

  3. JS数组中every(),filter(),forEach(),map(),some()方法学习笔记!

    ES5中定义了五种数组的迭代方法:every(),filter(),forEach(),map(),some(). 每个方法都接受两个参数:要在每一项运行的函数(必选)和运行该函数的作用域的对象-影响 ...

  4. Java中如何遍历Map对象的4种方法

    在java中遍历Map有不少的方法.我们看一下最常用的方法及其优缺点. 既然java中的所有map都实现了Map接口,以下方法适用于任何map实现(HashMap, TreeMap, LinkedHa ...

  5. Python特殊语法:filter、map、reduce、lambda [转]

    Python特殊语法:filter.map.reduce.lambda [转] python内置了一些非常有趣但非常有用的函数,充分体现了Python的语言魅力! filter(function, s ...

  6. JAVA的容器---List,Map,Set (转)

    JAVA的容器---List,Map,Set Collection├List│├LinkedList│├ArrayList│└Vector│ └Stack└SetMap├Hashtable├HashM ...

  7. 转!! Java中如何遍历Map对象的4种方法

    在Java中如何遍历Map对象 How to Iterate Over a Map in Java 在java中遍历Map有不少的方法.我们看一下最常用的方法及其优缺点. 既然java中的所有map都 ...

  8. Java 集合系列 15 Map总结

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  9. Java 集合系列 08 Map架构

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

随机推荐

  1. 微信小程序 - 配置普通二维码跳小程序

    普通二维码跳小程序规则: https://developers.weixin.qq.com/miniprogram/introduction/qrcode.html#%E5%8A%9F%E8%83%B ...

  2. C++ 第三课:常量转义字符

    常量转义字符 以下的转义字符使普通字符表示不同的意义. 转义字符 描述 \' 单引号 \" 双引号 \\ 反斜杠 \0 空字符 \a 响铃 \b 后退 \f 走纸 \n 换行 \r 回车 \ ...

  3. Elasticsearch cluster health: yellow unassigned shards

    查看ES各个分片的状态 $ curl -XGET http://127.0.0.1:9200/_cluster/health?pretty { "cluster_name" : & ...

  4. Tomcat访问日志浅析 (转)

    来自:http://blog.chinaunix.net/uid-20691565-id-3938220.html Tomcat的访问日志是靠org.apache.catalina.valves.Ac ...

  5. Nginx server之Nginx添加ssl支持

    //环境介绍 1.nginx服务器:10.10.54.157 2.配置nginx服务器,当监听到来自客户端www.zijian.com:80请求时,转到10.10.54.150:1500这个web服务 ...

  6. Xcode7安装CocoaPods

    一.CocoaPods介绍以及优点 CocoaPods 是开发 OS X 和 iOS 应用程序的一个第三方库的依赖管理工具.该项目源代码在Github上管理. 通过 CocoaPods,能够非常方便的 ...

  7. Android网络编程(一)HTTP协议原理

    相关文章 Android网络编程(一)HTTP协议原理 Android网络编程(二)HttpClient与HttpURLConnection Android网络编程(三)Volley使用方法全解析 A ...

  8. SpringBoot配置RestTemplate的代理和超时时间

    application.properties: #代理设置 proxy.enabled=false proxy.host=192.168.18.233 proxy.port=8888 #REST超时配 ...

  9. Office2013中文激活版

    国内的WPS专业版也是很不错的,习惯的Office.office2013很不错的办公利器 00.PPT 01.Word 02.Excel Download: 链接: https://pan.baidu ...

  10. UITextField的UIControlEventValueChanged事件

    关于UITextField的UIControlEventValueChanged事件无响应的问题 监听UITextField文本改变的事件不是使用这个枚举 而是使用 UIControlEventEdi ...