Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava: HashBasedTable that keeps insertion order?

Tags:

java

guava

I am in a need of a way to keep two keys for a value - exactly what Guavan's HashBasedTable does . The issue is that it does not keep the insertion order when iterating over values. Is there any elegant solution to get it working? It doesn't have to be Guava, but I wouldn't want to bloat my project with dependencies.

I am trying to use mentioned ImmutableTable - and I haven't found any example. I get NPE everywhere when building a table like that:

ImmutableTable<String, String, AbstractUnit> units;
ImmutableTable.Builder<String, String, AbstractUnit> builder =        units.builder();
builder.put(unit1.getType(), unit1.getName(), unit1);
...
units = builder.build();

I will get NPE when gettinb units.values(). Also, will I be able to modify values of AbstractUnit in the table?

like image 762
Paul Avatar asked Mar 20 '14 23:03

Paul


People also ask

How do you keep an insertion order on a map?

LinkedHashMap extends HashMap. It maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is,when iterating through a collection-view of a LinkedHashMap, the elements will be returned in the order in which they were inserted.

Does MAP maintain insertion order Java?

P.S HashMap does not guarantee insertion order.


3 Answers

You can specify the back-end map structure for your table. Specifying a LinkedHashMap will maintain the insertion order.

 Table<String,String,AbstractUnit> units = Tables.newCustomTable(new LinkedHashMap<>(), LinkedHashMap::new); 

I tried using the ImmutableMap as described by @Louis Wasserman and it was doing natural ordering instead.

like image 173
Ben L. Avatar answered Sep 21 '22 14:09

Ben L.


ImmutableTable will maintain insertion order, like all the other immutable collections.

like image 38
Louis Wasserman Avatar answered Sep 18 '22 14:09

Louis Wasserman


Since Guava 20.0, HashBasedTable maintains insertion order. Specifically:

Implementation of Table using linked hash tables. This guarantees predictable iteration order of the various views.

Internally it's backed by a LinkedHashMap.

like image 40
Jakg Avatar answered Sep 19 '22 14:09

Jakg