1

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);
2
  • If you initialize the ArrayList in your for loop, won't its contents be deleted or overwritten at each iteration of the loop? Commented Apr 29, 2015 at 23:01
  • 1
    Sometimes readability is worth one or two line more. (Personally I don't even like the one-line-for-if) Commented Apr 29, 2015 at 23:05

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately the project is written in Java 7. I don't have the ability to change that.
I know it's not proper style to condense the loop to one line. I was just trying to make it as compact as possible.
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.