Stuart Perera
Stuart Perera

Reputation: 1

How can I remove an entry from a map and reorder the entries via key value?

This is a little program I've been working on that tracks some money gains/losses in transactions.

I've basically finished it aside from this problem I have.

deleteItem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Map<Integer, Entry> newMap = new LinkedHashMap<>();
            if (table.getSelectedRow() != -1) {
                System.out.println(table.getSelectedRow() + 1);
                entryTable.removeEntry(table.getSelectedRow() + 1);
                entries.remove(table.getSelectedRow() + 1);

            }

            for(Map.Entry<Integer, Entry> entry : entries.entrySet()) {
                newMap.put(entry.getKey() - 1 == 1 ? 2 : entry.getKey() - 1, entry.getValue());
            }

            if (table.getRowCount() == 1) {
                Gui.this.saveAll();
            }
            entries = newMap;
            Gui.this.saveAll();
        }
    });

So this map gets put into a table and if I remove any entry but the first, all works fine. However, if I remove the first entry it removes, but the table doesn't resort itself and I've come to the conclusion it must be the map ordering.

Is there a way I can take the values of the map after an entry is removed and reorder them via their key value so that they remain in numerical order?

Upvotes: 0

Views: 85

Answers (1)

linkD
linkD

Reputation: 141

The problem with using LinkedHashMap for your problem is that it retains insertion order, not sorting by the actual keys.

Rather than storing the map entries in order, I'd recommend having your UI sort the entries when they're being displayed rather than when storing them. Imagine changing 100 map entries - the map would have to be sorted 100 times in the worst case possible, which is just unnecessary if you display it only once (it is very likely that you change the map more often than displaying/refreshing it).

Going with @jaredr's suggestion though, if you absolutely have to retain key order, have a look at SortedMap.

Upvotes: 1

Related Questions