Java 8 Map Filter 过滤示例_stream.filter过滤-CSDN博客

Java 8 Map Filter 过滤示例

Java 8之前:

String result = "";for (Map.Entry<Integer, String> entry : A_MAP_EXAMPLE.entrySet()) {    if("something".equals(entry.getValue())){        result = entry.getValue();    }}

在Java 8中,您可以转换Map.entrySet()stream由遵循filter()collect()它。

//Map -> Stream -> Filter -> StringString result = A_MAP_EXAMPLE.entrySet().stream()    .filter(map -> "something".equals(map.getValue()))    .map(map->map.getValue())    .collect(Collectors.joining()); //Map -> Stream -> Filter -> MAPMap<Integer, String> collect = A_MAP_EXAMPLE.entrySet().stream()    .filter(map -> map.getKey() == 2)    .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

Java 8 - 过滤地图

一个过滤Map并返回String的完整示例。

TestMapFilter.java

package com.mkyong.java8 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");         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);     }}

Output

之前Java 8:aws.amazon.com 使用Java 8:aws.amazon.com

2. Java 8 - 过滤Map#2

另一个过滤Map的例子,但这将返回一个Map。

TestMapFilter.java

package com.mkyong.java8 import java.util.HashMap;import java.util.Map;import java.util.stream.Collectors; public class TestMap {     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}     }}

原网址: 访问
创建于: 2024-06-19 16:50:01
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论