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));
    }
}
}
2
  • 1
    What makes you think that HashMap has any order, or even the same order on two separate iterations? From the documentation: "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". Commented Jan 21, 2017 at 9: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... :) Commented Jan 21, 2017 at 9:46

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.