2012-04-07 19 views
7

Mam przeczytać w pliku zawierającym wiele różnych adresów e-mail i wydrukować je za pomocą tablicy. Problem polega na tym, że muszę wyeliminować duplikaty wiadomości e-mail.Java Usuń duplikaty z tablicy?

Udało mi się przetestować mój try/catch i wydrukować adresy e-mail. Jednak nie jestem pewien, jak usunąć duplikaty. Nie mam jeszcze pojęcia o hashcode lub jak korzystać z Set. Każda pomoc będzie doceniona.

Oto co mam do tej pory:

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

szukasz najbardziej wydajne rozwiązanie możliwe? Jeśli nie, po prostu utwórz nową tablicę i wykonaj iterację po starej, dodając po sprawdzeniu, czy bieżący wpis jest już w nowej tablicy. – jli

+0

@jli powiedział tak przed tobą: P. To może nie być najskuteczniejsze rozwiązanie, ale piekło. –

+1

możliwe duplikat [Jak usunąć powtarzające się elementy z ArrayList?] (Http://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist) – Mark

Odpowiedz

2

Można spróbować przeżywa każdego elementu tablicy, dodając go do innego, sprawdzając czy 2nd tablica zawiera kolejny element, jeśli nie pominąć to. Następnie wymień pierwszą tablicę na drugą. (ArrayList jest jednak lepszy w tym przypadku).

więc coś takiego:

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

pierwszą rzeczą, która przychodzi mi do głowy to, aby posortować tablicę, a następnie sprawdzić, czy kolejny element równa bieżącego elementu. jeśli tak, usuń bieżący element.

oh i kiedy nie wiesz, ile e-maili jest przechowywanych w pliku, tablica prawdopodobnie nie jest najlepszym sposobem. Zrobiłbym jakąś listę, więc nie muszę się martwić, ile adresów e-mail jest w pliku.

+1

nie ma żadnego punktu sortowania. – Kevin

-1

można napisać funkcję, która działa na tablicy i wziąć jeden adres e-mail na raz, a gdy tylko znajdzie ten sam adres, ustaw go na wartość null. kiedy używasz na tablicy, aby go wydrukować, zrobić warunek, aby wydrukować e-mail tylko wtedy, gdy nie jest pusta

31

Prostym rozwiązaniem jest, że stosowanie Zestaw Java,

tak ustawić usunąć duplikaty wartość automatycznie

w kodzie masz tablicę niż przekształcić tablicę ustawić bezpośrednio za pomocą kodu

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

+1 to jest najprostsze rozwiązanie – jli

+0

+1, nigdy nie użyłem skrótów, chociaż posiadanie listy <> może być przydatne = 3 –

+1

dzięki. Myślę, że mogę to wypróbować - nigdy przedtem nie słyszałem o setach, ponieważ dopiero zaczynam programować. Więc co to jest i co robi plik .asList? –

4

Dowiedz się Set. Czas potrzebny, aby się go nauczyć, jest krótszy niż czas potrzebny na zakodowanie czegoś, co go nie wykorzystuje.

Zacznę od ciebie.Zastąpić to:

String[] address = new String[100];

z tym:

Set<String> addresses = new HashSet<String>();

a to:

address[i] = email;

z tym:

addresses.add(email);

Nie trzeba już się i.

Skończyłeś. Jeśli chcesz wydrukować wszystko:

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

To prawie obejmuje. Chcesz, aby wszystko zostało automatycznie posortowane? Wymień powyższy HashSet na TreeSet. Teraz przeczytaj this excellent tutorial, aby następnym razem zrobić to szybciej i na własną rękę.

+0

dzięki ... wydaje się dość łatwe, ale muszę używać tablic –

+1

Czy możesz mi powiedzieć coś więcej o ograniczeniach zadania? Jestem zaskoczony, że pozwalają one tylko na używanie tablic, biorąc pod uwagę, że lista adresów wydaje się mieć dowolną długość (w przeciwieństwie do stałej długości tablicy). –

1

Użyj klasy ArrayUtil, jak potrzebujesz. Napisałem kilka metod innych niż usuwanie duplikatów. Ta klasa jest zaimplementowana bez użycia jakichkolwiek klas struktury kolekcji.

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

Proszę użyć poniższego kodu do usunięcia duplikatów w tablicy całkowitej.

/* 
 
* 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) { 
 

 
\t // Store unique items in result. 
 
\t ArrayList<Integer> result = new ArrayList<>(); 
 

 
\t HashSet<Integer> set = new HashSet<>(); 
 

 
\t 
 
\t for (Integer item : list) { 
 

 
\t  
 
\t  if (!set.contains(item)) { 
 
\t \t result.add(item); 
 
\t \t set.add(item); 
 
\t  } 
 
\t } 
 
\t return result; 
 
    } 
 

 
    public static void main(String[] args) { 
 

 
\t ArrayList<Integer> list = new ArrayList<>(); 
 
\t list.add(12); 
 
\t list.add(12); 
 
\t list.add(8); 
 
\t list.add(6); 
 
\t list.add(4); 
 
\t list.add(4); 
 
     list.add(2); 
 
     list.add(1); 
 
      //int a[]={12,12,8,6,4,4,2,1} 
 
\t 
 
\t ArrayList<Integer> unique = removeDuplicates(list); 
 
\t for (int element : unique) { 
 
\t  System.out.println(element); 
 
\t } 
 
    } 
 
} 
 

 
/*run: 
 
12 
 
8 
 
6 
 
4 
 
2 
 
1 
 
BUILD SUCCESSFUL (total time: 0 seconds)*/

0

Jeśli chcesz usunąć duplikaty można spróbować coś takiego:

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