Domanda

I created a multimap like this:

private ListMultimap<String, int[]> terrainMap = ArrayListMultimap.create();
{
    terrainMap.put("Terrain.Ground", new int[] {0,100,300,0});
    terrainMap.put("Terrain.Ground", new int[] {300,200,400,0});
    terrainMap.put("Terrain.Ground", new int[] {400,250,800,0});
    terrainMap.put("Terrain.Ground", new int[] {800,500,810,0});
    terrainMap.put("Terrain.DestroyableBlock", new int[] {100,200,150,150});
    terrainMap.put("Terrain.DestroyableBlock", new int[] {500,400,600,350});
};

And I want to display it in this specific order, but when I use foreach loop to do so:

for(Map.Entry<String, int[]> entry : terrainMap.entries())
{
   System.out.println(entry.getKey());
}

I get the following results:

Terrain.DestroyableBlock
Terrain.DestroyableBlock
Terrain.Ground
Terrain.Ground
Terrain.Ground
Terrain.Ground

As if it automatically sorted keys alphabetically in the map. Can I turn it off?

È stato utile?

Soluzione

The Javadoc of ArrayListMultimap specifies: "A HashMap associates each key with an ArrayList of values." So, like a HashMap, keys are ordered arbitrarily.

It sounds like you might want LinkedListMultimap or MultimapBuilder.linkedHashKeys().arrayListValues().build().

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top