2012-04-07 42 views
7

Tôi phải đọc trong một tệp có chứa nhiều địa chỉ email khác nhau và in chúng ra bằng một mảng. Vấn đề là tôi cần phải loại bỏ các email trùng lặp.Java Xoá các bản sao khỏi một mảng?

Tôi đã có thể sử dụng thử/bắt tay và in ra các địa chỉ email. Tuy nhiên, tôi không chắc chắn làm thế nào để đi về việc loại bỏ các bản sao. Tôi chưa hiểu về hashcode hoặc cách sử dụng Set. Bất kỳ trợ giúp sẽ được đánh giá cao.

Dưới đây là những gì tôi có cho đến nay:

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

Bạn đang tìm kiếm các giải pháp hiệu quả nhất có thể? Nếu không, chỉ cần tạo một mảng mới và lặp qua một mảng cũ, thêm khi bạn đi sau khi kiểm tra xem mục nhập hiện tại đã có trong mảng mới chưa. – jli

+0

@jli vừa nói trước bạn: P. Nó có thể không phải là giải pháp hiệu quả nhất, nhưng địa ngục. –

+1

có thể trùng lặp của [Làm thế nào để loại bỏ các yếu tố lặp đi lặp lại khỏi ArrayList?] (Http://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist) – Mark

Trả lời

2

Bạn có thể thử đi qua từng phần tử trong mảng, thêm nó vào nhau, kiểm tra nếu các mảng thứ 2 chứa chi tiết tiếp theo, nếu có thì bỏ qua nó. Sau đó, chỉ thay thế mảng thứ nhất bằng thứ 2. (ArrayList là tốt hơn trong trường hợp này mặc dù).

nên một cái gì đó như thế này:

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

điều đầu tiên mà đi vào đầu của tôi là để sắp xếp mảng và sau đó để kiểm tra xem phần tử tiếp theo bằng các yếu tố hiện tại. nếu có, hãy xóa phần tử hiện tại.

oh và khi bạn không biết số lượng email được lưu trữ trong tệp, mảng có thể không phải là cách tốt nhất. Tôi sẽ lấy một số loại danh sách, do đó tôi không phải quan tâm có bao nhiêu địa chỉ e-mail trong tệp.

+1

không có điểm phân loại. – Kevin

-1

bạn có thể viết một hàm chạy trên mảng và nhận một email cùng một lúc và khi nào nó tìm thấy cùng một địa chỉ chỉ cần đặt nó thành rỗng. khi bạn đang chạy trên mảng in nó, làm cho một điều kiện để in các email chỉ nếu không null

31

Giải pháp đơn giản là sử dụng rằng Đặt java,

để thiết lập loại bỏ giá trị trùng lặp một cách tự động

và trong mã của bạn, bạn có mảng hơn chuyển đổi mảng để thiết lập trực tiếp sử dụng mã

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

+1 đây là giải pháp đơn giản nhất – jli

+0

+1, tôi chưa bao giờ băm, mặc dù có Danh sách <> có thể hữu ích = 3 –

+1

cảm ơn. Tôi đoán tôi có thể thử nó-tôi chưa bao giờ nghe nói về bộ trước khi tôi mới bắt đầu lập trình. Vì vậy, những gì là và những gì hiện các .asList làm gì? –

4

Tìm hiểu Set. Thời gian nó sẽ đưa bạn đến tìm hiểu nó là ít hơn thời gian nó sẽ đưa bạn đến mã cái gì đó không sử dụng nó.

Tôi sẽ giúp bạn bắt đầu.Thay thế này:

String[] address = new String[100];

với điều này:

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

Và đây:

address[i] = email;

với điều này:

addresses.add(email);

Bạn không cần i nữa.

Bạn đã hoàn tất. Nếu bạn muốn in mọi thứ ra:

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

Điều đó khá nhiều. Muốn mọi thứ được sắp xếp tự động? Thay thế HashSet ở trên bằng TreeSet. Bây giờ, hãy đọc số this excellent tutorial để lần sau, bạn có thể hoàn thành công việc nhanh hơn và tự làm.

+0

cảm ơn ... có vẻ dễ dàng đủ nhưng tôi được yêu cầu sử dụng mảng –

+1

Bạn có thể cho tôi biết thêm một chút về những hạn chế của nhiệm vụ? Tôi ngạc nhiên rằng họ chỉ cho phép bạn sử dụng mảng, xem xét rằng danh sách các địa chỉ dường như có chiều dài tùy ý (so với độ dài cố định của một mảng). –

1

Sử dụng lớp ArrayUtil khi bạn cần. Tôi đã viết một số phương pháp khác ngoài việc loại bỏ các bản sao. Lớp này được triển khai mà không sử dụng bất kỳ lớp khung Bộ sưu tập nào.

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

Vui lòng sử dụng mã bên dưới để xóa các từ khóa trùng lặp trong một mảng nguyên.

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

Nếu bạn muốn loại bỏ bản sao bạn có thể thử một cái gì đó như thế này:

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 
    } 
} 
Các vấn đề liên quan