不按排序顺序计算数组中每个元素的出现顺序

时间:2018-10-09 16:03:20

标签: java

我正在尝试计算数组中每个元素的频率。但是有一个限制是我不想按排序顺序打印元素。

我的输入就像

7 1 2 1 1 6 8 7

,并且输出采用这种格式     {1 = 3,2 = 1,6 = 1,7 = 2,8 = 1}

我不想要

我的输出应类似于

7 2 

1 3 

2 1

6 1

8 1

对于上述输入。而且我不需要任何定界符

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int n=s.nextInt();
        int a[]=new int[n],temp=0,count=0,flag=-1,b[]=new int[n];
        for(int i=0;i<n;i++)
        {
            a[i]=s.nextInt();
        }
        Map<Integer,Integer> hm = new HashMap();

        for(int x:a){
            if(!hm.containsKey(x)){
                hm.put(x,1);
            }else{
                hm.put(x, hm.get(x)+1);
            }
        }
        System.out.println(hm);
    }
}

3 个答案:

答案 0 :(得分:2)

使用LinkedHashMap来保持插入顺序。然后使用

hm.entrySet().forEach(e ->  System.out.println(e.getKey() + " " + e.getValue()));

不仅要打印地图,还需要遍历地图并打印每个键和值。

答案 1 :(得分:0)

如果您不想使用随机顺序或排序顺序,则应该可以使用LinkedHashMap,它会在打印时为您提供插入顺序迭代。那时,@ Nicholas K的打印格式解决方案效果很好。

答案 2 :(得分:0)

如果您继续使用HashMap

,这是一种替代方法
Iterator<Entry<Integer, Integer>> iter = hm.entrySet().iterator();

while (iter.hasNext()) {
    Entry<Integer, Integer> entry = iter.next(); 
    System.out.println(entry.getKey() + " " + entry.getValue());
}
相关问题