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 ie 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
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.