Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 计算给定数组中的重复元素_Java_Arrays - Fatal编程技术网

Java 计算给定数组中的重复元素

Java 计算给定数组中的重复元素,java,arrays,Java,Arrays,如何计算给定数组中的重复元素?请给我一些建议,作为这个问题的替代方案 public static void main(String[] args) { // TODO Auto-generated method stub int a[]={1,2,3,1,2,4,4,4,5}; int c=0; for(int i=0;i!='\0';i++) { c=1; for(int k=i+1;k<9;k++)

如何计算给定数组中的重复元素?请给我一些建议,作为这个问题的替代方案

public static void main(String[] args) 
{
    // TODO Auto-generated method stub
    int a[]={1,2,3,1,2,4,4,4,5};
    int c=0;
    for(int i=0;i!='\0';i++)
    {
        c=1;
        for(int k=i+1;k<9;k++)
        {
            if(a[i]==a[k] && a[i]!='\0')
            {
                c++;
               // a[k]='\0';
            }
        }
        if(a[i]!='\0')
        {
            System.out.println("value is"+a[i]+"repeated in"+c);
            System.out.println("\n");
        }
    }
}
publicstaticvoidmain(字符串[]args)
{
//TODO自动生成的方法存根
int a[]={1,2,3,1,2,4,4,4,5};
int c=0;
for(int i=0;i!='\0';i++)
{
c=1;

对于(int k=i+1;k,这里有另一种不需要单独数据结构的简单方法:

  • 使用静态方法对数组进行排序
  • 现在,您可以遍历数组,知道所有重复项都将分组在一起
从以下位置窃取我的代码:


您可以使用array.length方法而不是i!='\0',iYou不应该用Java编写C。我的意思是,您应该用Java的方式编写,正如@DaanMouha所说,使用a.length。
public static void main(String[] args) throws Exception {
    int[] a = {1, 2, 3, 1, 2, 4, 4, 4, 5};
    final Counter<Integer> counter = new Counter<>();
    IntStream.of(a).forEach(counter::add);
    IntStream.rangeClosed(1, 5).forEach(i -> {
        System.out.printf("%s has a count of %s%n", i, counter.count(i));
    });
}

public static class Counter<T> {
    final Map<T, Integer> counts = new HashMap<>();

    public void add(T t) {
        counts.merge(t, 1, Integer::sum);
    }

    public int count(T t) {
        return counts.getOrDefault(t, 0);
    }
}
1 has a count of 2
2 has a count of 2
3 has a count of 1
4 has a count of 3
5 has a count of 1