首页 > 解决方案 > 如何在java中返回过滤后的Hashmap的值?

问题描述

所以HashMap我创建了这个并继续使用 lambda 和 Stream 过滤它:

public class engineMain {

    public static void main(String[] args) {
        CarEngine engineOne = new CarEngine("A named Engine", 2000, 8, "E10");
        CarEngine engineTwo = new CarEngine("Another named Engine", 2200, 6, "E10");
        String a = "Another named Engine";
        HashMap<String, CarEngine> hmap = new HashMap();
        hmap.put(engineOne.getEngineName(), engineOne);
        hmap.put(engineTwo.getEngineName(), engineTwo);
        hmap.entrySet().stream().filter(e -> e.getValue().getEngineName().contains(a))
                .forEach(e -> System.out.println(e));
    }

}

如何改进我的最后一行代码,使其返回过滤后的值?现在它返回:Another named Engine=javaapplication40.CarEngine@6ce253f1

我也尝试过这种方式

HashMap<String, CarEngine> map = new HashMap<>();
map.entrySet().stream().filter(x -> x.getKey().equals(a))
        .flatMap(x -> ((Map<String, CarEngine>) x.get(a)).values().stream())
        .forEach(System.out::println);

标签: javaoopcollectionshashmapjava-stream

解决方案


看来您正在寻找:

CarEngine find = hmap.values().stream()
                   .filter(e -> e.getEngineName().contains(a)) 
                   .findFirst() 
                   .orElse(null);

推荐阅读