简体   繁体   English

How to use Java Stream API to iterate through a HashMap with custom object

[英]How to use Java Stream API to iterate through a HashMap with custom object

I have a hashmap with key as object below我有一个 hashmap,下面的键为 object

I want to be able to iterates through the hashmap, and retrieves values only for keys matching name and second value in symbol ie lmn, hij我希望能够遍历 hashmap,并仅检索与符号中的名称和第二个值匹配的键的值,即 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示例:如果输入是pqrhij ,结果应该返回 500。我希望能够使用 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

Quick and dirty:又快又脏:

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

It may be better to just create a predicate that checks the product:最好只创建一个检查产品的谓词:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM