Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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_Duplicates - Fatal编程技术网

Java是否从数组中删除重复项?

Java是否从数组中删除重复项?,java,arrays,duplicates,Java,Arrays,Duplicates,我应该读入一个包含许多不同电子邮件地址的文件,然后用数组打印出来。问题是我需要消除重复的电子邮件 我能够让我的try/catch工作并打印出电子邮件地址。但是,我不知道如何删除重复项。我还不了解hashcode,也不知道如何使用Set。任何协助都将不胜感激 以下是我到目前为止的情况: import java.util.Scanner; import java.io.*; public class Duplicate { public static void main(String[] a

我应该读入一个包含许多不同电子邮件地址的文件,然后用数组打印出来。问题是我需要消除重复的电子邮件

我能够让我的try/catch工作并打印出电子邮件地址。但是,我不知道如何删除重复项。我还不了解hashcode,也不知道如何使用
Set
。任何协助都将不胜感激

以下是我到目前为止的情况:

import java.util.Scanner;
import java.io.*;

public class Duplicate {
   public static void main(String[] args) {

      Scanner keyboard = new Scanner(System.in);
      System.out.println("Enter file name: ");
      String fileName = keyboard.nextLine();
      if (fileName.equals("")) {
         System.out.println("Error: User did not specify a file name.");
      } else {
         Scanner inputStream = null;

         try {
            inputStream = new Scanner(new File(fileName));
         } catch (FileNotFoundException e) {
            System.out.println("Error: " + fileName + " does not exist.");
            System.exit(0);
         }

         String[] address = new String[100];

         int i = 0;
         while (inputStream.hasNextLine()) {
            String email = inputStream.nextLine();
            // System.out.println(email);

            address[i] = email;
            System.out.println(address[i]);
            i++;
         }
      }
   }
}

您可以尝试遍历数组中的每个元素,将其添加到另一个元素中,检查第二个数组是否包含下一项,如果它确实跳过它。然后用第二个数组替换第一个数组。(
ArrayList
在这种情况下更好)

比如说:

List<String> FinalList = new ArrayList<String>();
for(string temp : adress)
{
if(!FinalList.contains(temp))
  FinalList.add(temp);
}
String[] address = new String[100]; // the array that contains all addresses
ArrayList<String> uniqueAddresses = new ArrayList<String>(); // create arraylist to contain all non-repeated addresses
for(String addr : address){ // cycle through the entire array
   if(!uniqueAddresses.contain(addr)){ // check if the address already there
      uniqueAddresses.add(addr); // add it
   }
}
List FinalList=new ArrayList();
用于(字符串温度:地址)
{
如果(!FinalList.contains(temp))
最终添加(临时);
}

我想到的第一件事是对数组进行排序,然后检查下一个元素是否等于当前元素。如果是,请删除当前元素


哦,当你不知道文件中存储了多少封电子邮件时,数组可能不是最好的方法。我会选择某种列表,这样我就不必关心文件中有多少个电子邮件地址。

您可以编写一个在数组上运行的函数,每次接收一封电子邮件,当它找到相同的地址时,只需将其设置为空。
当您在阵列上运行以打印电子邮件时,请设定一个条件,仅当其不为null时才打印电子邮件。简单的解决方案是使用java

所以设置自动删除重复值

在您的代码中有数组,而不是直接使用代码将数组转换为集合

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
Set mySet=newhashset(Arrays.asList(someArray));
将它们读入一个文件中。这将为您处理重复项

Set<String> addresses = new HashSet<String>();
addresses.add("a@a.com");
addresses.add("a@a.com");
addresses.add("a@a.com");
System.out.println(addresses.size());
Set addresses=newhashset();
地址。添加(“a@a.com");
地址。添加(“a@a.com");
地址。添加(“a@a.com");
System.out.println(addresses.size());

将打印
1

学习
Set
。学习它所花费的时间比编写不使用它的代码所花费的时间要少

我会让你开始的。替换此项:

String[]地址=新字符串[100]

为此:

Set addresses=newhashset()

这是:

地址[i]=电子邮件

为此:

地址。添加(电子邮件)

你不再需要
i

你完了。如果要打印所有内容,请执行以下操作:

for (String address : addresses) {
     System.out.println (address);
}

这差不多涵盖了它。希望所有内容都自动排序吗?将上面的
HashSet
替换为
TreeSet
。现在开始阅读,以便下次您可以更快地自己完成所有工作。

根据需要使用ArrayUtil类。除了删除重复项,我还编写了一些方法。此类是在不使用任何集合框架类的情况下实现的

public class ArrayUtils {
/**
 * Removes all duplicate elements from an array. 
 * @param arr Array from which duplicate elements are to be removed.
 * @param removeAllDuplicates true if remove all duplicate values, false otherwise 
 * @return Array of unique elements.
 */
public static int[] removeDuplicate(int[] arr, boolean removeAllDuplicates)         {
    int size = arr.length;

    for (int i = 0; i < size;) {
        boolean flag = false;

        for (int j = i + 1; j < size;) {
            if (arr[i] == arr[j]) {
                flag = true;
                shrinkArray(arr, j, size);
                size--;
            } else
                j++;
        }

        if (flag && removeAllDuplicates) {
            shrinkArray(arr, i, size);
            size--;
        } else
            i++;
    }

    int unique[] = new int[size];
    for (int i = 0; i < size; i++)
        unique[i] = arr[i];

    return unique;
}

/**
 * Removes duplicate elements from an array. 
 * @param arr Array from which duplicate elements are to be removed.
 * @return Array of unique elements.
 */
public static int[] removeDuplicate(int[] arr) {
    return removeDuplicate(arr, false);
}


private static void shrinkArray(int[] arr, int pos, int size) {
    for (int i = pos; i < size - 1; i++) {
        arr[i] = arr[i + 1];
    }
}

/**
 * Displays the array.
 * @param arr The array to be displayed.
 */
public static void displayArray(int arr[]) {
    System.out.println("\n\nThe Array Is:-\n");

    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + "\t");
    }
}

/**
 * Initializes the array with a given value.
 * @param arr The array to be initialized.
 * @param withValue The value with which the array is to be initialized.
 */
public static void initializeArray(int[] arr, int withValue) {
    for (int i = 0; i < arr.length; i++) {
        arr[i] = withValue;
    }
}

/**
 * Checks whether an element is there in the array. 
 * @param arr The array in which the element is to be found.
 * @param element The element that is to be found.
 * @return True if found false otherwise
 */
public static boolean contains(int arr[], int element) {
    for(int i=0; i< arr.length; i++) {
        if(arr[i] == element)
            return true;
    }

    return false;
}

/**
 * Removes a element from an array.
 * @param arr The array from which the element is to removed.
 * @param element The element to be removed
 * @return The size of the array after removing.
 */
public static int removeElement(int[] arr, int element) {
    int size = arr.length;
    for(int i=0; i< arr.length; i++){
        if(arr[i] == element){
            shrinkArray(arr, i, arr.length);
            size--;
        }
    }
    return size;
}

/**
 * Counts unique elements in an array.
 * @param arr The required array.
 * @return Unique element count.
 */
public static int uniqueElementCount(int arr[]) {
    int count = 0;
    int uniqueCount=0;
    int[] consideredElements = new int[arr.length];

    initializeArray(consideredElements, 0);

    for(int i=0;i<arr.length;i++) {
        int element = arr[i];
        for(int j=i+1;j<arr.length; j++){
            if(element != arr[j] && !contains(consideredElements, element)){
                consideredElements[count++] = element;
            }
        }
    }

    for(int i=0;i< consideredElements.length;i++)
        if(consideredElements[i]!=0)
            uniqueCount++;

    return uniqueCount;
}
}
公共类数组直到{
/**
*从数组中删除所有重复的元素。
*@param arr数组,从中删除重复元素。
*@param removeAllDuplicates如果删除所有重复值,则为true,否则为false
*@返回唯一元素的数组。
*/
公共静态int[]removeDuplicate(int[]arr,布尔removeAllDuplicates){
int size=arr.length;
对于(int i=0;iT[] array = {…};
Set<T> set = Set.copyOf(Arrays.asList(array));
Arrays.stream(array).distinct().toArray(T[]::new);