Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Java Guava library, how to create a ImmutableSortedSet using a Builder?

I'm sure this is a very simple question but please take a look at the code sample below:

final ImmutableSortedSet<String> notOk = ImmutableSortedSet.naturalOrder().build();         
final ImmutableSortedSet<String> ok = new ImmutableSortedSet.Builder<String>(Ordering.natural()).build();
final ImmutableList<String> typicalGuava = ImmutableList.of("one", "two");

I'm just wondering what is the proper way to use the naturalOrder() method in the first example? In that example Java cannot infer the type so you get a "type mismatch" error.

like image 251
Dave L. Avatar asked Sep 11 '26 18:09

Dave L.


2 Answers

With a series of chained calls like that, the compiler is unable to infer the type argument for the call to naturalOrder() since its result is not immediately assigned to something it can use for inference.

You can write

ImmutableSortedSet<String> ok = ImmutableSortedSet.<String>naturalOrder().build();

or

ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder();
// ...
ImmutableSortedSet<String> ok = builder.build();
like image 197
ColinD Avatar answered Sep 13 '26 07:09

ColinD


Do this:

final ImmutableSortedSet<String> nowOk = ImmutableSortedSet.<String>naturalOrder().build();
like image 32
Dilum Ranatunga Avatar answered Sep 13 '26 06:09

Dilum Ranatunga



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!