Joiner not ordering correctly?

485 views Asked by At

I have the following code to to run Joiner to concat keys. However, they show up out of order.

    BiMap<String, String> whatever= HashBiMap.create();
    {
        whatever.put("First group", "f1");
        whatever.put("This should really be second", "f2");
        whatever.put("3rd group", "f3");
    }
    String groups = Joiner.on('|').join(whatever.keySet());
    System.out.println(groups);

output:

This should really be second|3rd group|First group

expected output:

First group|This should really be second|3rd group

How do I get these to show up in order because it's important considering they are going to evaluated in a boolean expresion?

2

There are 2 answers

1
Sowry On BEST ANSWER

HashBiMap.keySet returns a set which is an unordered data structure. So your join call could be in any order.

As suggested by Louis, as you are using the Guava Library, you can make use of the available methods for sorting collections, using: Ordering.natural().sortedCopy(Collection collection)

then the final line would be:

Collection<String> unsorted = whatever.values();
List<String> sorted = Ordering.natural().sortedCopy(unsorted) 
String groups = Joiner.on('|').join(sorted);
System.out.println(groups);

This would only sort by alphabetical order (i think).

If an immutability is acceptable, you can use ImmutableBiMap, which does preserve the insertion ordering. Otherwise, I would suggest creating a method which would sort the data yourself (either by extending BiMap, or a static method).

0
Giovanni Botta On

You are creating a HashBiMap which doesn't preserve the order. You need a list for that. Or if you want alphabetical order some kind of sorted BiMap.