3

Hi I have created a logic to calculate duplicates in an array list, But it's not printing in the exact order that i want. Below i have provided my code and my requirement.

I need in below format,

list: [1, 1, 5, 3, 7, 3, 11, 2, 3, 1]
number: 1, count: 3
number: 5, count: 1
number: 3, count: 3
number: 7, count: 1
number: 11, count: 1
number: 2, count: 1

But, I am getting in below format,

list: [1, 1, 5, 3, 7, 3, 11, 2, 3, 1]
number: 1, count: 3
number: 2, count: 1
number: 3, count: 3
number: 5, count: 1
number: 7, count: 1
number: 11, count: 1

Here's my code

package com.abc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyArrayListSort
{
public static void main(String []args){
    new MyArrayListSort().start();
}
public void start()
{
    List<Integer> list = getList(1, 1, 5, 3, 7, 3, 11, 2, 3, 1);

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (Integer i : list)
    {
        Integer retrievedValue = map.get(i);
        if (null == retrievedValue)
        {
            map.put(i, 1);
        }
        else
        {
            map.put(i, retrievedValue + 1);
        }
    }

    System.out.println("list: " + list);
    printCount(map);
}

private List<Integer> getList(int... numbers)
{
    List<Integer> list = new ArrayList<Integer>();
    for (int i : numbers)
    {
        list.add(i);
    }
    return list;
}

private void printCount(Map<Integer, Integer> map)
{
    for (Integer key : map.keySet())
    {
        System.out.println("number: " + key + ", count: " + map.get(key));
    }
}
}
Sritam Jagadev
  • 955
  • 4
  • 18
  • 46
  • 1
    What makes you think that `HashMap` has **any order**, or even the same order on two separate iterations? From [the documentation](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html): "_This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time_". – Boris the Spider Jan 21 '17 at 09:44
  • I tried to use hashmap to get the result in my desired order ....but if you can help me in this without using hashmap then it wil be better... :) – Sritam Jagadev Jan 21 '17 at 09:46

1 Answers1

3

Use LinkedHashMap, which maintains insertion order, instead of HashMap:

public void start() {
    List<Integer> list = getList(1, 1, 5, 3, 7, 3, 11, 2, 3, 1);

    Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
    for (Integer i : list) {
        Integer retrievedValue = map.get(i);
        if (null == retrievedValue) {
            map.put(i, 1);
        }
        else {
            map.put(i, retrievedValue + 1);
        }
    }

    System.out.println("list: " + list);
    printCount(map);
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360