Google Guava: how to use ImmutableSortedMap.naturalOrder?

I am using Google Guava r08 and JDK 1.6.0_23.

I want to create ImmutableSortedMapusing the builder. I know that I can create a builder as follows:

ImmutableSortedMap.Builder<Integer, String> b1 =
    new ImmutableSortedMap.Builder<Integer, String>(Ordering.natural());

and then use this to build maps, for example:

ImmutableSortedMap<Integer, String> map =
    b1.put(1, "one").put(2, "two").put(3, "three").build();

I noticed that the class ImmutableSortedMaphas a method naturalOrder()that returns Builderwith natural ordering. However, when I try to call this method, I get strange errors. For example, this gives a strange "expected" error:

// Does not compile
ImmutableSortedMap.Builder<Integer, String> b2 =
    ImmutableSortedMap<Integer, String>.naturalOrder();

What is the correct syntax for calling a method naturalOrder()?

The API documentation of this method mentions some compiler error. Does this have anything to do with this method, doesn't work?

change

Mforster . , " ":

// Doesn't work, can't infer the types properly
ImmutableSortedMap<Integer, String> map =
    ImmutableSortedMap.naturalOrder().put(1, "one").put(2, "two").put(3, "three").build();

:

ImmutableSortedMap<Integer, String> map =
    ImmutableSortedMap.<Integer, String>naturalOrder().put(1, "one").put(2, "two").put(3, "three").build();
+3
2

ImmutableSortedMap.Builder<Integer, String> b2 =
    ImmutableSortedMap.<Integer, String>naturalOrder();

, :

ImmutableSortedMap.Builder<Integer, String> b2 =
    ImmutableSortedMap.naturalOrder();
+10

:

ImmutableSortedMap.Builder<Integer, String> b2 =
ImmutableSortedMap.<Integer, String>naturalOrder();

( , , )

+5

Source: https://habr.com/ru/post/1790175/


All Articles