Java 8 – Filter a Map examples
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的更多相关文章
- react+redux教程(三)reduce()、filter()、map()、some()、every()、...展开属性
reduce().filter().map().some().every()....展开属性 这些概念属于es5.es6中的语法,跟react+redux并没有什么联系,我们直接在https:// ...
- Java集合框架之map
Java集合框架之map. Map的主要实现类有HashMap,LinkedHashMap,TreeMap,等等.具体可参阅API文档. 其中HashMap是无序排序. LinkedHashMap是自 ...
- JS数组中every(),filter(),forEach(),map(),some()方法学习笔记!
ES5中定义了五种数组的迭代方法:every(),filter(),forEach(),map(),some(). 每个方法都接受两个参数:要在每一项运行的函数(必选)和运行该函数的作用域的对象-影响 ...
- Java中如何遍历Map对象的4种方法
在java中遍历Map有不少的方法.我们看一下最常用的方法及其优缺点. 既然java中的所有map都实现了Map接口,以下方法适用于任何map实现(HashMap, TreeMap, LinkedHa ...
- Python特殊语法:filter、map、reduce、lambda [转]
Python特殊语法:filter.map.reduce.lambda [转] python内置了一些非常有趣但非常有用的函数,充分体现了Python的语言魅力! filter(function, s ...
- JAVA的容器---List,Map,Set (转)
JAVA的容器---List,Map,Set Collection├List│├LinkedList│├ArrayList│└Vector│ └Stack└SetMap├Hashtable├HashM ...
- 转!! Java中如何遍历Map对象的4种方法
在Java中如何遍历Map对象 How to Iterate Over a Map in Java 在java中遍历Map有不少的方法.我们看一下最常用的方法及其优缺点. 既然java中的所有map都 ...
- Java 集合系列 15 Map总结
java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...
- Java 集合系列 08 Map架构
java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...
随机推荐
- Linux shell中一些参数与变量简介
linux中shell变量$#,$@,$0,$1,$2,$!,$$,$*,$-,$@......等很多个,很容易记错,这里再次整理一下,相关含义解释如下,并附上一个实践截图. 多看几次,多用几次,应该 ...
- 微软BI 之SSAS 系列 - 多维数据集中度量值设计时的聚合函数 (累加性_半累加性和非累加性)
在 SSAS 系列 - 实现第一个 Cube 以及角色扮演维度,度量值格式化和计算成员的创建 中主要是通过已存在的维度和事实数据创建了一个多维数据集,并同时解释了 Role-Playing Dimen ...
- 實戰ESXi 5設置MPIO 打造IP-SAN負載平衡容錯
http://www.netadmin.com.tw/article_content.aspx?sn=1305100002 測試MPIO負載平衡及容錯移轉機制VMware vSphere ESXi主機 ...
- 分享一个CSS+JavaScript框架materializecss
一.内容: CSS+JavaScript框架materializecss. 二.网址:http://materializecss.com 三.图片:
- 【推荐】ImageProcessor.Web,再也不用自己生成缩略图了
1.什么是ImageProcessor.Web ImageProcessor.Web是基于ImageProcessor的web图像处理模块,允许开发者使用URL查询字符串参数的方式作为指令执行图像处理 ...
- 忘记MySQL root密码重置MySQL root密码
(1)停止mysql# /etc/init.d/mysql stop(2)以不检查权限的方式启动# mysqld --skip-grant-tables &(3)登录mysql修改root用户 ...
- unity3d与web网页通信
总结一下: Unity3D 中的 C# 和 JavaScript 脚本之间是可以互相访问并交互的,但是要求这些被访问和操作的 C# 和 JavaScript 组件必须放在名为 Standard Ass ...
- mysql安装后服务启动不了
1.1 前言 最近真的是倒霉到家,装个mysql都能把所有的问题给问候了一遍······不过这也是一个宝贵的经验,得好好总结下,毕竟也不知道以后会不会再次遇到.如果有网友也能像我这样倒霉,但是能够幸运 ...
- SSM实战——秒杀系统之Web层Restful url设计、SpringMVC整合、页面设计
一:Spring整合SpringMVC 1:编写web.xml,配置DispatcherServlet <web-app xmlns="http://java.sun.com/xml/ ...
- 【DB2】表空间相关详细说明
-.创建表空间 1.创建用户表空间 声明:在指定表空间创建路径的时候,需要指定空文件夹,非空文件夹会导致创建报错!!!如果文件夹不存在,那么在创建表空间的时候会自动创建文件夹! 1.1 创建SMS表空 ...