Reputation: 1595
I have a collection of Account objects. I would like to stream through this collection and filter based on if the price is greater than 100. Then add only those account ids to a List
This is what I have using forEach
List<String> filteredAcctList = new ArrayList<String>()
forEach(Account acct:accountList){
if(acct.getPrice() >100){
filteredAcctList.add(acct.getAccountId())
}
}
I am trying to accomplish the same using the Java 8 stream but not sure how to create an ArrayList of just the account Ids.
Upvotes: 1
Views: 6492
Reputation: 1537
You need to use map
in order to "map" your Account
items into String
.
List<String> filteredAccList =
accountList
.stream()
.filter(a -> a.getPrice() > 100)
.map(Account::getAccountId)
.collect(Collectors.toList());
Upvotes: 3