HashMap: iterating the key-value pairs in random order

后端 未结 3 818
误落风尘
误落风尘 2021-01-18 03:43

I have a HashMap and I\'d like to iterate they key-value pairs in a different random order each time i get the iterator. Conceptually I\'d like to \"shuffle\" the map before

3条回答
  •  隐瞒了意图╮
    2021-01-18 04:21

    Try use concurent hash map and get key by random before iteration cycle

    Map map = Maps.newConcurrentMap();
    
            map.put("1", "1");
            map.put("2", "2");
            Iterator iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                map.remove("2");// add random key values
                map.put("2", "2");
                String next = iterator.next();
                System.out.println("next" + next);
            }
    

    Random remove/put values can "shuffle" your map

提交回复
热议问题