Donald Raab
Mar 4, 2021

--

Sometimes writing a for-loop is the best answer. But this can be done using a special kind of Procedure or for this particular question, you could just use partition. Here's a code example showing CaseProcedure and partition in Eclipse Collections:

MutableList<Integer> evens = Lists.mutable.empty();

MutableList<Integer> odds = Lists.mutable.empty();

MutableList<Integer> numbers = Lists.mutable.with(1, 2, 3, 4, 5);

numbers.forEach(new CaseProcedure<Integer>()

.addCase(e -> e % 2 == 0, evens::add)

.addCase(e -> e % 2 != 0, odds::add));

System.out.println(evens);

System.out.println(odds);

PartitionMutableList<Integer> partition = numbers.partition(each -> each % 2 == 0);

Assert.assertEquals(evens, partition.getSelected());

Assert.assertEquals(odds, partition.getRejected());

If you ask the question on StackOverflow, it would be easier to answer and might benefit others. There is a question there already I answered should how to use CaseFunction to solve FizzBuzz in Java 8.

https://stackoverflow.com/questions/37814655/fizzbuzz-using-jdk8-lambda

--

--

Donald Raab
Donald Raab

Written by Donald Raab

Java Champion. Creator of the Eclipse Collections OSS Java library (https://github.com/eclipse/eclipse-collections). Inspired by Smalltalk. Opinions are my own.

No responses yet