0

i make a linkedhashmap like this in java using netbean

LinkedHashMap map = new LinkedHashMap();

 map.put(0, "one");
 map.put(1, "two");
 map.put(2, "three");

in the above code the key(0,1,2), i want that it auto generate. I try different online solution but doesn't work.

naeem
  • 43
  • 8

3 Answers3

1

You can use map.size():

map.put(map.size(), "one"); // map.size() returns 0
map.put(map.size(), "two"); // map.size() returns 1
map.put(map.size(), "three"); // map.size() returns 2
...
Eran
  • 387,369
  • 54
  • 702
  • 768
0
public class Main {
    public static void main(String[] args) {
        Map<Integer, String> map = new LinkedHashMap<>();
        map.put(KeyGenerator.getNextKey(), "One");
        map.put(KeyGenerator.getNextKey(), "Two");
        map.put(KeyGenerator.getNextKey(), "Three");
        map.forEach((key, value) -> System.out.println("Key = " + key + ", value = " + value));
    }

    static class KeyGenerator {
        private static AtomicInteger key = new AtomicInteger(0);
        public static int getNextKey() {
            return key.getAndAdd(1);
        }
    }
}
0
public class Test {

    static int i = 0;

    public static void main(String[] args) {

        Map<Integer, String> map = new LinkedHashMap<>();
        map.put(getNext(), "One");
        map.put(getNext(), "Two");
        map.put(getNext(), "Three");
        map.forEach((key, value) -> System.out.println("Key = " + key + ", value = " + value));
    }

    static int getNext() {
        i = i+1;
        return i;
    }
}
  • thanks it helps a lot.. Thanks Narendra for your ans it help, i have one more problem i do hope you will find it interested. stackoverflow.com/questions/49677006/… – naeem Apr 05 '18 at 16:28