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. SQL Server Window Function 窗体函数读书笔记一 - SQL Windowing

    SQL Server 窗体函数主要用来处理由 OVER 子句定义的行集, 主要用来分析和处理 Running totals Moving averages Gaps and islands 先看一个简 ...

  2. [转发]如何在ASP.NET的web.config配置文件中添加MIME类型

    常常有一些特殊的MIME类型是IIS中没有的,一般来说要我们自己手动添加.如果网站经常更换服务器或者网站代码是提供给多个用户使用,那么会造成网站中用到的特殊的MIME类型要经常性的在IIS上配置.这里 ...

  3. 分享自己针对Automation做的两个成熟的框架(QTP 和Selenium)

    自己在google code中开源了自己一直以来做的两个自动化的框架,一个是针对QTP的一个是针对Selenium的,显而易见,一个是商业的UI automation工具,一个是开源的自动化工具. 只 ...

  4. 小结java自带的跟锁相关的一些类

    java.util.concurrent包下的一些跟锁相关的类列表  类  简介 locks.Lock接口 Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作.此 ...

  5. Mybatis-Dao层开发之Mapper接口

    Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法. Mapper接口开发 ...

  6. grep命令-v参数过滤以井号、分号开头的注释信息行及空白行

    grep命令-v参数(反向选择)分别去掉所有以#(井号)和;(分号)开头的注释信息行,对于剩余的空白行可以再用^$来表示并反选过滤 [root@rhel7 samba]# cat smb.conf | ...

  7. weblogic部署存在中文乱码导致部署失败

    问题描述: weblogic控制台显示错误,是受管节点console日志 <-- 下午10时19分16秒 CST> <Info> <Security> <BE ...

  8. 使用Adobe Audition 处理声音步骤

      软件: Adobe Audition 3.0 处理声音 插件:单独安装各种DirectX音效处理插件    一.录音 * 录音笔.手机 * Adobe Audition专业的录音软件   二..润 ...

  9. FTP命令字和响应码解释

    FTP命令: 命令  描述  ABOR 中断数据连接程序 ACCT <account> 系统特权帐号 ALLO <bytes>  为服务器上的文件存储器分配字节 APPE &l ...

  10. 用@resource注解方式完成属性装配

    注入依赖对象可以采用手工装配或自动装配,在实际应用中建议使用手工装配,因为自动装配会产生未知情况,开发人员无法预见最终的装配结果. 1 需要修改xml文件的以下信息.    加入下列红色部分的4行 & ...