Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable initialization from intermediate result

Tags:

java

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?

like image 453
steffen Avatar asked Mar 13 '26 15:03

steffen


1 Answers

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);
like image 76
Andy Turner Avatar answered Mar 15 '26 03:03

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!