HashMap: iterating the key-value pairs in random order

后端 未结 3 856
误落风尘
误落风尘 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:27

    Reshuffling a large collection is always going to be expensive. You are going to need at least one reference per entry. e.g. for 1 million entries you will need approx 4 MB.

    Note; the shuffle operation is O(N)

    I would use

    Map map = 
    List> list = new ArrayList>(map.entrySet());
    
    // each time you want a different order.
    Collections.shuffle(list);
    for(Map.Entry entry: list) { /* ... */ }
    

提交回复
热议问题