首页 > 解决方案 > How to use Java Stream API to iterate through a HashMap with custom object

问题描述

I have a hashmap with key as object below

I want to be able to iterates through the hashmap , and retrieves values only for keys matching name and second value in symbol i.e lmn , hij

Example: if input is pqr and hij , result should return 500. I want to be able to do this using Java stream API

class Product {
   String name;
   String symbol;
}

Example values

    KEY.               VALUE
name symbol
abc  12|lmn|standard   1000
pqr  14|hij|local      500

标签: javajava-stream

解决方案


又快又脏:

map.entrySet().stream()
    .filter(e -> e.getKey().name.equals(nameMatch))
    .filter(e -> e.getKey().symbol.contains("|" + keyMatch + "|"))
    .map(e -> e.getValue()).findFirst().orElse(null);

最好只创建一个检查产品的谓词:

Predicate<Product> matcher = matcher(nameMatch, symbolMatch);
Integer result = map.entrySet().stream()
    .filter(e -> matcher.test(e.getKey()))
    .map(e -> e.getValue()).findFirst().orElse(null);

...

private static Predicate<Product> matcher(String name, String symbolPart) {
    String symbolMatch = "|" + symbolPart + "|";
    return product -> product.name.equals(name) &&
        product.symbol.contains(symbolMatch);
}


推荐阅读