genxgeek
genxgeek

Reputation: 13357

Joiner not ordering correctly?

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?

Upvotes: 1

Views: 488

Answers (2)

Sowry
Sowry

Reputation: 105

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).

Upvotes: 4

Giovanni Botta
Giovanni Botta

Reputation: 9816

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.

Upvotes: 0

Related Questions