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?
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.
P.S HashMap does not guarantee insertion order.
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.
ImmutableTable
will maintain insertion order, like all the other immutable collections.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With