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. 微信小程序 - 下拉刷新(非组件)

    详情见示例:refresh

  2. Word转PDF非常好用的软件——pdfFactory Pro

    pfdFactory Pro把word转为pdf的操作步骤: 1.打开将要转换的word的文档: 2.文件--->打印: 弹出如下对话框: 单击确定后弹出:

  3. hadoop old API CombineFileInputFormat

    来自:http://f.dataguru.cn/thread-271645-1-1.html 简介 本文主要介绍下面4个方面 1.为什么要使用CombineFileInputFormat 2.Comb ...

  4. HTML5开发之获取设备的地理坐标

    近期一段时间開始学一下html5,发现里面有好多的知识还是蛮新颖的.所以整理了一下自己练习过的demo给大家分享下,以下的代码是通过js接口获取当前的地理坐标. <!doctype html&g ...

  5. Python学习笔记七:pip

    安装pip: 到github上下载pip:https://github.com/pypa/pip 解压后,在解压出来的文件夹中打开命令行,输入 python setup.py install 安装完毕 ...

  6. Java AtomicBoolean (Java代码实战-008)

    值得一提的是,Java的AtomXXX类并不是使用了锁的方式进行同步,而是采用了一种新的理念,叫做CAS(Compare And Swap)CAS是一组CPU原语指令,用来实现多线程下的变量同步(原子 ...

  7. ssh无法登录,提示Pseudo-terminal will not be allocated because stdin is not a terminal.

    当远程通过ssh登录主机时出现Pseudo-terminal will not be allocated because stdin is not a terminal. 错误   字面意思是伪终端将 ...

  8. 上海期货交易所CTP行情和交易接入

    发布时间:2018-09-25   技术:C++11,动态库的制作   概述 CTP的接入Demo 详细 代码下载:http://www.demodashi.com/demo/14125.html 本 ...

  9. sqlserver几个好用的表值函数和标量函数

    获取逗号风格的字符串中的某一个 比如'1,2,4,5,6' 第三个就是4 CREATE function [dbo].[Get_StrArrayStrOfIndex] ( @str nvarchar( ...

  10. centos 7 系统启动不了 出现报错dependency failed for /mnt , dependency failed for local file systems

    阿里云一台Ecs重启后启动不了,出现报错 dependency failed for /mnt , dependency failed for local file systems ,  报错的原因  ...