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 ...
随机推荐
- C#实现U盘检查,并写入文件
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- 如何设置Vmware下Linux系统全屏显示
环境:Vmware10+RedHat5 在Vmware10中安装好RedHat5后,即使点击了全屏按钮(或使用快捷键Ctrl+Alt+Enter),全屏的效果依然不尽人意,跟下图中差不多,RedHat ...
- JavaScript的valueOf和toString
深度好文 http://www.cnblogs.com/coco1s/p/6509141.html 知识要点 不同对象调用valueOf和toString的顺序不一样 高阶函数的使用,替代for循环 ...
- 关于CBC for ios 加密要记
倒腾了接近半天,资料找了无数,最后是通过查看Android项目中的加密工具类,才弄明白,在这过程中掌握了一些知识点.比如: 问题1:关于PKCS7Padding和PKCS5Padding iOS中AE ...
- Jquery为动态添加的未来元素绑定事件
语法: $(selector).on(event,childSelector,data,function) event:必需.规定要从被选元素移除的一个或多个事件或命名空间.由空格分隔多个事件值,也可 ...
- 【Linux】创建不可修改文件
有时候,我们害怕别人修改我们创建的文件,或者是误删我们创建的文件,那么我们可以使用下面的方法进行控制即可 1.创建不可删除文件 Linux:/qinys/oliver # touch test.sh ...
- SpringCloud之搭建配置中心
一.搭建config-server 1.引入pom <dependencies> <dependency> <groupId>org.springframework ...
- yum实现仅仅下载不安装包
问题的产生,都是源于真实的需求... 01.yum安装切保存rpm包于本地 [root@yhs_web_1 ~]# vim /etc/yum.conf [main] cachedir=/var/cac ...
- Unrecognized option: -jrockit
weblogic报错: starting weblogic with Java version: Unrecognized option: -jrockit Error: Could not crea ...
- 转:Ogre源码分析之Root类、Facade模式
Ogre源码分析(一)Root类,Facade模式 Ogre中的Root对象是一个Ogre应用程序的主入口点.因为它是整个Ogre引擎的外观(Façade)类.通过Root对象来开启和停止Ogre是最 ...