1

I need the last input from HashMap to be deleted then, add a new input instead.I heard you can do that using LinkedHashMap, but how exactly? The instructions didn't mention that I should use LinkedHashMap but apparently, it is impossible to remove the last item from a HashMap without it.

Or if you have any alternative solutions that would remove the last item so I could add the other input, do tell me what I should add to the code.

Here is what I am trying to do:

package studentlist;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class StudentList {

    public static void main(String[] args) {
        
        Map<String, String> students = new HashMap<>();
        
        Scanner s = new Scanner(System.in);
        
        for(int i=1; i<= 3; i++){
             
            System.out.print("Enter student number " + i + ": ");  
            String es = s.nextLine();
            
            System.out.print("Enter student first name " + i + ": ");
            String en = s.nextLine();
            
            students.put(es, en);
            
        }
      
        for (Map.Entry mp : students.entrySet()) {
            System.out.println(mp.getKey()  +  " "  + mp.getValue());
        }
      
        //The 3rd input should be removed before this:

        System.out.print("Enter your student number: ");  
        String sn = s.nextLine();
            
        System.out.print("Enter your first name: ");
        String fn = s.nextLine();
            
        students.put(sn, fn);
            
        for (Map.Entry mp : students.entrySet()) {
            System.out.println(mp.getKey()  +  " "  + mp.getValue());
        }
    }
}
Lutzi
  • 416
  • 2
  • 13
Ciel
  • 25
  • 6

2 Answers2

1

Just some ideas:

  • Keep a variable where you store the the last entered student
  • Keep 2 structures (a list and a map)
  • Iterate the LinkedHashMap to the end to find the last entry.
Reto Höhener
  • 5,419
  • 4
  • 39
  • 79
1

The javadoc of Map says:

The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

The javadoc of LinkedHashMap says:

[LinkedHashMap] maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

So, to remove the last inserted (not re-inserted) entry, use any of the 3 iterators, skip to the end, and remove the entry:

static <K, V> Entry<K, V> removeLast(LinkedHashMap<K, V> map) {
    Iterator<Entry<K, V>> entryIter = map.entrySet().iterator();
    if (! entryIter.hasNext())
        return null;
    Entry<K, V> entry;
    do {
        entry = entryIter.next();
    } while (entryIter.hasNext());
    entryIter.remove();
    return entry;
}

Test

LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("A", "1");
map.put("E", "5");
map.put("B", "2");
map.put("D", "4");
map.put("E", "6"); // Re-insert
map.put("C", "3");

for (int i = 0; i < 7; i++)
    System.out.println(removeLast(map));

Output

C=3
D=4
B=2
E=6
A=1
null
null

No-one said it was going to be fast, but this would be how to do it, with just the Map. Especially useful if you need to remove multiple entries without inserting new entries in-between.

Depending on need, it might be better to simply remember the last key on the side. With that, you can quickly remove the last inserted key, but you couldn't e.g. remove the second-last key by doing the "remove last" twice.

Andreas
  • 154,647
  • 11
  • 152
  • 247