【问题标题】:Java Remove Duplicates from an Array?Java从数组中删除重复项?
【发布时间】:2012-04-20 20:28:46
【问题描述】:

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

我能够让我的 try/catch 工作并打印出电子邮件地址。但是,我不确定如何删除重复项。我还不了解哈希码或如何使用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++;
         }
      }
   }
}

【问题讨论】:

  • 您是否正在寻找最有效的解决方案?如果没有,只需创建一个新数组并遍历旧数组,然后在检查当前条目是否已在新数组中后添加。
  • @jli 刚刚在你之前说过:P。这可能不是最有效的解决方案,但地狱。
  • @Bean Winz - 欢迎来到 stackoveflow。以后,如果您的问题是家庭作业,请务必添加homework 标签。

标签: java arrays duplicates


【解决方案1】:

简单的解决方案是使用Java的Set,

所以设置自动删除重复值

在您的代码中,您有数组而不是转换数组以直接使用代码设置

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));

【讨论】:

  • 谢谢。我想我可以尝试一下——因为我刚刚开始编程,所以我以前从未听说过套装。那么 是什么,.asList 有什么作用呢?
  • 嗨 Bean,如果你使用 Set mySet = new HashSet(Arrays.asList(someArray));比它好,但如果你想创建一组特定的数据类型,那么你可以给出数据类型而不是 T ex Set set = new Hashset();.
  • T 是您要使用的任何数据类型的占位符(在您的情况下为String)。这个符号对于刚开始的人来说有点高级,所以现在不要担心。先学习this collections tutorial之类的基础知识,遇到T的东西会显得更自然一些。
  • 谢谢我刚刚弄清楚了那部分。但我对把这段代码放在哪里感到困惑。我会把它放在我的while循环中吗?
  • 没有。首先在while 循环中构建数组,然后在数组完成后将其转换为集合。然后检查集合,将所有地址打印出来。你可以使用类似for(String s : mySet) System.out.println(s);
【解决方案2】:

了解Set。您学习它所花费的时间少于编写不使用它的代码所花费的时间。

我会带你开始的。替换这个:

String[] address = new String[100];

用这个:

Set&lt;String&gt; addresses = new HashSet&lt;String&gt;();

还有这个:

address[i] = email;

用这个:

addresses.add(email);

您不再需要i

你已经完成了。如果您想打印所有内容:

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

这几乎涵盖了它。想要所有东西都自动排序吗?将上面的HashSet 替换为TreeSet。现在去阅读this excellent tutorial,以便下次您可以更快地自己完成所有工作。

【讨论】:

  • 你能告诉我更多关于作业的限制吗?我很惊讶他们只允许你使用数组,考虑到地址列表似乎是任意长度(相对于数组的固定长度)。
【解决方案3】:

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

所以是这样的:

List<String> FinalList = new ArrayList<String>();
for(string temp : adress)
{
if(!FinalList.contains(temp))
  FinalList.add(temp);
}

【讨论】:

    【解决方案4】:

    改为将它们读入HashSet。这将为您处理重复项。

    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());
    

    将打印1

    【讨论】:

      【解决方案5】:

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

      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;
      }
      }
      

      【讨论】:

        【解决方案6】:

        请使用以下代码删除整数数组中的重复项。

        /*
         * To change this license header, choose License Headers in Project Properties.
         * To change this template file, choose Tools | Templates
         * and open the template in the editor.
         */
        package test123;
        
        import java.util.ArrayList;
        import java.util.HashSet;
        
        /**
         *
         * @author krawler
         */
        public class Test123 {
        
            /**
             * @param args the command line arguments
             */
             public static ArrayList<Integer> removeDuplicates(ArrayList<Integer> list) {
        
        	// Store unique items in result.
        	ArrayList<Integer> result = new ArrayList<>();
        
        	HashSet<Integer> set = new HashSet<>();
        
        	
        	for (Integer item : list) {
        
        	   
        	    if (!set.contains(item)) {
        		result.add(item);
        		set.add(item);
        	    }
        	}
        	return result;
            }
        
            public static void main(String[] args) {
        
        	ArrayList<Integer> list = new ArrayList<>();
        	list.add(12);
        	list.add(12);
        	list.add(8);
        	list.add(6);
        	list.add(4);
        	list.add(4);
                list.add(2);
                list.add(1); 
                   //int a[]={12,12,8,6,4,4,2,1}
        	
        	ArrayList<Integer> unique = removeDuplicates(list);
        	for (int element : unique) {
        	    System.out.println(element);
        	}
            }
        }
        
        /*run:
        12
        8
        6
        4
        2
        1
        BUILD SUCCESSFUL (total time: 0 seconds)*/

        【讨论】:

          【解决方案7】:

          如果您想删除重复项,可以尝试以下操作:

          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
             }
          }
          

          【讨论】:

            【解决方案8】:

            从数组中删除重复项

            T[] array = {…};
            


            得到一个 Set 没有重复
            从 Java 10 开始

            Set<T> set = Set.copyOf(Arrays.asList(array));
            

            数组元素的顺序会丢失


            得到一个新的数组没有重复的

            Arrays.stream(array).distinct().toArray(T[]::new);
            

            保留数组元素的顺序

            【讨论】:

              【解决方案9】:

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

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

              【讨论】:

                【解决方案10】:

                您可以编写一个在数组上运行的函数,一次接收一封电子邮件,当它找到相同的地址时,只需将其设置为 null。 当您在阵列上运行以打印它时,仅当它不为空时才打印电子邮件的条件

                【讨论】:

                  猜你喜欢
                  • 2014-04-16
                  • 2014-04-23
                  • 2011-06-29
                  • 2021-03-02
                  • 2023-03-20
                  • 1970-01-01
                  • 2011-01-04
                  相关资源
                  最近更新 更多