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

I am sure this is a very simple question, but please take a look at the sample code 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 how to use the naturalOrder () method in the first example correctly? In this example, Java cannot infer the type so that you get a "type mismatch" error.

+3
source share
2 answers

With this sequence of chain calls, the compiler cannot output a type argument for the call naturalOrder(), since its result is not immediately assigned to what it can use for output.

You can write

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

or

ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder();
// ...
ImmutableSortedSet<String> ok = builder.build();
+5
source

Do it:

final ImmutableSortedSet<String> nowOk = ImmutableSortedSet.<String>naturalOrder().build();
+3
source

All Articles