Sometimes, when source code gets complicated, I find it confusing to read statements like these:
Set<Integer> odds = new HashSet<>(ints); // not yet true
odds.removeAll(evens); // now it's true
I was wondering if there's a clever way to avoid a line where odds contains also even values. Something similar to this:
(Set<Integer> odds = new HashSet<>(ints)).removeAll(evens); // doesn't compile
I could use double brace initialization,
Set<Integer> odds = new HashSet<Integer>(ints) {{ removeAll(evens); }};
but that's obviously bad for multiple reasons.
Here's another example hack that compiles, but it looks more like a joke:
Set<Integer> odds = (odds = new HashSet<>(ints)).retainAll(evens) ? odds : odds
The last one that came to my mind (while writing this) seems to be ok, although it uses two lines:
Set<Integer> odds;
(odds = new HashSet<Integer>(ints)).removeAll(evens);
Any other ideas?
Use a stream:
Set<Integer> odds =
ints.stream().filter(x -> x % 2 == 1).collect(Collectors.toSet());
If you want to partition the set into odds and evens at the same time:
Map<Boolean, Set<Integer>> oddsAndEvens =
ints.stream().collect(
Collectors.partitioningBy(x -> x % 2 == 0, Collectors.toSet()));
Set<Integer> evens = oddsAndEvens.get(true);
Set<Integer> odds = oddsAndEvens.get(false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With