从数组中删除重复项。打印hashmap时出错

时间:2013-08-14 19:53:24

标签: java map hashmap set

import java.util.*;
public class RemoveDuplicates {

private static Scanner ak;

public static void main(String[] args) {
    ak = new Scanner(System.in);
    int k=0;
    System.out.println("enter the size of the array");
    int n=ak.nextInt();
    int a[]=new int[n];
    for (int i=0;i<n;i++){
        System.out.println("enter element "+(i+1));
        a[i]=ak.nextInt();
    }
    Arrays.toString(a);
    HashMap<Integer,Integer> h=new HashMap<Integer, Integer>();
    for (int i=0;i<n;i++){
        if ((h.containsKey(a[i]))){
            k=h.get(a[i]);
            h.put(a[i],k+1);
        }
        else{
            h.put(a[i], 1);
        }
    }

    System.out.print(h);
    Set <Map.Entry<Integer, Integer>> c=h.entrySet();

    System.out.print(c);
    System.out.println("these are the duplicates removed elements  ");

    Iterator<Map.Entry<Integer, Integer>> i=c.iterator();
    while (i.hasNext()){
        if (i.next().getValue()==1)
        System.out.println(i.next().getKey());

    }
  }
}

我编写了一个程序,使用HashMap从数组中删除重复项,但我无法打印正确的输出。 当我输入size = 4的输入时 并且数组输入为{1,1,2,3} 迭代器仅打印&#34; 3&#34;应该打印的地方&#34; 2,3&#34; 任何帮助将不胜感激

2 个答案:

答案 0 :(得分:6)

这是问题所在:

if (i.next().getValue()==1)
System.out.println(i.next().getKey());

您在一次迭代中调用next()两次 - 因此您要检查一个条目的计数,然后打印以进行下一次条目。 (你的缩进很糟糕。)你想要的东西是:

while (i.hasNext()) {
    Map.Entry<Integer, Integer> entry = i.next();
    if (entry.getValue() == 1) {
        System.out.println(entry.getKey());
    }
}

或使用增强的for循环使其更简单:

for (Map.Entry<Integer, Integer> entry : c) {
    if (entry.getValue() == 1) {
        System.out.println(entry.getKey());
    }
}

答案 1 :(得分:0)

做你想做的最简单的方法是:

Integer[] arr = ....
INteger[] arr2 = new LinkedHashSet<Integer>(Arrays.asList(arr)).toArray(new Integer[0]);

此时arr2仅以相同的顺序包含源数组的唯一元素。 如果要打印数组使用

System.out.println(Arrays.toString(arr2));