在数组中查找重复的字符串元素&在java中计算该elecment的出现次数

时间:2016-12-15 19:51:37

标签: java arrays

    public static void main(String[] args) {
    String[] strArray = { "Islamabad", "Gilgit", "Nawabshah", "Karachi",
            "Abbotabad", "Gilgit", "Hyderabad", "Islamabad", "Lahore",
            "Hyderabad", "Sukkur", "Faisalabad", "Kohat", "Faisalabad",
            "Faisalabad", "Bhakkar", "Faisalabad", "Lahore", "Abbotabad",
            "Attock", "Karachi", "Rawalpindi", "Nawab Shah", "Abbotabad",
            "Sukkur", "Attock", "Multan", "Faisalabad", "Multan", "Sukkur" };
    System.out.println("Length : " + strArray.length);

    Arrays.sort(strArray);

    for (int i = 0; i < strArray.length - 1; i++) {
        for (int j = i + 1; j < strArray.length; j++) {
            if ((strArray[i].equals(strArray[j])) && (i != j)) {
                System.out.println("Duplicate Element is : " + strArray[j]);
            }
        }
    }

    HashSet<String> set = new HashSet<String>();
    for (int i = 0; i < strArray.length; i++) {
        // If same integer is already present then add method will return
        // FALSE
        if (set.add(strArray[i]) == false) {
            System.out.println("Duplicate element found : " + strArray[i]);
        }
    }
}

I have tried both methods following this but none of them give any accurate result, it doesn't work for the my number of array elements

2 个答案:

答案 0 :(得分:1)

如果您使用的是Java 8,则可以使用StreamCollectors

import java.util.Arrays;
import java.util.stream.Collectors;

class Main {
  public static void main(String[] args) {
    String[] strArray = { "Islamabad", "Gilgit", "Nawabshah", "Karachi",
            "Abbotabad", "Gilgit", "Hyderabad", "Islamabad", "Lahore",
            "Hyderabad", "Sukkur", "Faisalabad", "Kohat", "Faisalabad",
            "Faisalabad", "Bhakkar", "Faisalabad", "Lahore", "Abbotabad",
            "Attock", "Karachi", "Rawalpindi", "Nawab Shah", "Abbotabad",
            "Sukkur", "Attock", "Multan", "Faisalabad", "Multan", "Sukkur" };

    System.out.format("The length of the array is: %d%n%n", strArray.length);

    System.out.println("Duplicate String Elements and their count is shown below:");

    Arrays.stream(strArray)
      .collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> {if(v.size() > 1) System.out.println(k+" "+v.size());});

  }
}

输出:

The length of the array is: 30

Duplicate String Elements and their count is shown below:
Faisalabad 5
Gilgit 2
Islamabad 2
Hyderabad 2
Attock 2
Karachi 2
Multan 2
Lahore 2
Sukkur 3
Abbotabad 3

试试here!

答案 1 :(得分:0)

我只是想编辑你的代码来打印字符串的副本数量:

static int count;
int i,j;
 for ( i = 0; i < strArray.length - 1; i++) {
       count=0;
    for ( j = i + 1; j < strArray.length; j++) {
        if ((strArray[i].equals(strArray[j])) && (i != j)) {
            count++;
        }
    }
 System.out.println("Duplicate Element is : " + strArray[j]+"Its occurrences are:"+count);
}