Reputation: 13216
If I have a List<Map<String, String>>
object such as this currencyList
:
0
0 = "product_id" -> 145
1 = "currency" -> USD
1
0 = "product_id" -> 105
1 = "currency" -> EUR
2
0 = "product_id" -> 102
1 = "currency" -> EUR
How do I then filter where currency=EUR
?
Something like...
List<Map<String, String>> eurCurrencyList
= currencyList.stream()
.anyMatch(map -> map.containsValue("EUR"));
but that doesn't return a boolean
but returns a map
like this:
0
0 = "product_id" -> 105
1 = "currency" -> EUR
1
0 = "product_id" -> 102
1 = "currency" -> EUR
Upvotes: 1
Views: 4067
Reputation: 17920
You need to use filter
to filter and can collect to list using Collectors.toList()
.
List<Map<String, String>> eurCurrencyList = currencyList.stream()
.filter(map -> map.containsValue("EUR"))
.collect(Collectors.toList());
EDIT:
If the map can have many entries, it may be inefficient to use containsValue
. Instead you can do .filter(map -> map.containsKey(key) && map.get(key).equals(value))
as mentioned in YCF_L@'s answer.
Upvotes: 4
Reputation: 60045
How do I then filter where currency=EUR?
You have to use filter
like so :
String key = "currency", value = "EUR";
List<Map<String, String>> eurCurrencyList = currencyList.stream()
.filter(map -> map.containsKey(key) && map.get(key).equals(value))
.collect(Collectors.toList());
Note, Instead of :
map.containsValue("EUR")
You have to use :
.filter(map -> map.containsKey(key) && map.get(key).equals(value))
You have to check if the map contain that key and the value.
Upvotes: 4