Reputation: 7879
Is there a way to combine the two commands below into a single line, where I initialize the ArrayList using the for-loop?
ArrayList<KSE> kseList = new ArrayList<KSE>();
for (KSE k : allKSEs) if (k.isKeyPress()) kseList.add(k);
The variable allKSEs
is just a generic Collection
Collection<KSE> allKSEs = KSE.parseSessionToKSE(ksListString);
Upvotes: 1
Views: 1359
Reputation: 4841
If you still use Java 7 you can use Apache CollectionUtils, Apache BeanUtils and the following code:
ArrayList<KSE> kseList = CollectionUtils.select(allKSEs, new BeanPropertyValueEqualsPredicate("keyPress", true));
Upvotes: 0
Reputation: 361625
In Java 8, you can use the new streaming syntax:
List<KSE> kseList = allKSEs.stream()
.filter(KSE::isKeypress)
.collect(Collectors.toList());
Pre-Java 8, what you have is what I would write, though I wouldn't condense the loop into a single line.
Upvotes: 3