Reputation: 11
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
Upvotes: 0
Views: 397
Reputation: 761
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);
}
Upvotes: 1