Welcome to the Ranch
James Mac wrote:. . . to replace a key you need to first remove the key that is going to be replace and put a new one. But that doesn't save the position of the removed key and value. . . .
No, you are correct. A hash map doesn't have any concept about the order of its
K‑V pairs. So you are going to have to use something different if you want to retain insertion order
and replace a
K in the same position as its predecessor was. Remember that if your map already contains that
K, calling
put() a
V against that
K, you will have something completely different happen (I think you know that already).
I suggest you go back to the Java™ Tutorials and look at the two pages about Maps, and remind yourself of their capabilities, If I haven't made a mistake about your requirements, I don't think any of the types shown there will do. I think, if you put() anything with a new K into a linked hash map, the implementation will perceive that as a new K and put that last in the accompanying list, so it will be out of order.I suggest you try searching for Apache Commons Bidirectional Map or Google Guava Bidirectional Map; maybe a bidirectional map will allow you to change the K on its own.I suggest you consider a plain simple hash map, accompanied by a list for your Ks. Whenever you are altering a K, you can find it in the accompanying List and call set() on that List. I suggest you find out about the performance of that technique if you have a large map (maybe 1,000,000 pairs)I suggest you consider two maps, one being a Mao<String, Long> where the V represents the insertion position. Again find out about the likely performance of such a second map with a large collection.I did wonder whether you could write your own map implementation whereby you can change a K directly, but I think that won't work.I suggest you will learn quite a lot when you read all that lot.
Find out about ways to copy maps; you will probably find that most implementations have copy constructors. Much better to use such a constructor that trying copying with
clear() and
addAll().
There are all sorts of things in your code which could be improved; I hven't got the time to tell you about everything, but there are two things I shall mention:-
1: You shouldn't create a new Scanner to read from System.in for each method call. You only need one Scanner reading System.in for the whole application.2: It is usually an error to make something static without a good explanation. I think you should have multiple classes and shorten your main method.Well done producing an interesting and unusual question