Ane*_*h K 2 java hashmap map 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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我编写了一个程序,使用HashMap从数组中删除重复项,但我无法打印正确的输出.当我输入输入为size = 4并且数组输入为{1,1,2,3}时,迭代器仅打印"3",因为它应该打印"2,3" 任何帮助将不胜感激
这就是问题:
if (i.next().getValue()==1)
System.out.println(i.next().getKey());
Run Code Online (Sandbox Code Playgroud)
你next()在一次迭代中调用了两次 - 所以你要检查一个条目的计数,然后打印下一个条目的密钥.(你的缩进很糟糕.)你想要的东西:
while (i.hasNext()) {
Map.Entry<Integer, Integer> entry = i.next();
if (entry.getValue() == 1) {
System.out.println(entry.getKey());
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用增强的for循环使其更简单:
for (Map.Entry<Integer, Integer> entry : c) {
if (entry.getValue() == 1) {
System.out.println(entry.getKey());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
551 次 |
| 最近记录: |