Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java xóa phần tử trùng lặp từ ArrayList


Trong bài viết này, chúng ta sẽ hiểu cách xóa phần tử trùng lặp từ ArrayList. Lớp ArrayList là mảng có thể thay đổi kích thước (resizable array), nằm trong package java.util. Khác với mảng built-in, kích thước ArrayList trong Java có thể thay đổi.

Minh họa dưới đây:

Giả sử đầu vào là:

Input list : [150, 250, 300, 250, 500, 150, 600, 750, 300]

Đầu ra mong muốn:

The list with no duplicates is: [150, 250, 300, 500, 600, 750]

Thuật toán

Bước 1 - BẮT ĐẦU 
Bước 2 - Khai báo biến 
Bước 3 - Định nghĩa giá trị 
Bước 4 - Tạo ArrayList số nguyên, khởi tạo phần tử 
Bước 5 - Hiển thị ArrayList 
Bước 6 - Tạo LinkedHashSet số nguyên 
Bước 7 - Dùng 'addAll' thêm phần tử từ ArrayList trước vào Set 
Bước 8 - Vì là Set, chỉ thêm giá trị duy nhất 
Bước 9 - Xóa phần tử ArrayList 
Bước 10 - Hiển thị Set với phần tử duy nhất 
Bước 11 - DỪNG

Ví dụ 1

Gom tất cả thao tác dưới hàm 'main'.

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.LinkedHashSet; 
import java.util.Set; 

public class Demo { 
    public static void main(String[] args) { 
        System.out.println("The required packages have been imported"); 
        ArrayList input_list = new ArrayList<>(Arrays.asList(150, 250, 300, 250, 500, 150, 600, 750, 300)); 
        System.out.println("The list is defined as: " + input_list); 
        Set temp_set = new LinkedHashSet<>(); 
        temp_set.addAll(input_list); 
        input_list.clear(); 
        input_list.addAll(temp_set); 
        System.out.println("\nThe list with no duplicates is: \n" + input_list); 
    } 
}

Kết quả

The required packages have been imported 
The list is defined as: [150, 250, 300, 250, 500, 150, 600, 750, 300] 
The list with no duplicates is: [150, 250, 300, 500, 600, 750]

Ví dụ 2

Đóng gói thao tác vào hàm thể hiện lập trình hướng đối tượng.

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.LinkedHashSet; 
import java.util.Set; 

public class Demo { 
    static void remove_duplicates(ArrayList input_list){ 
        Set temp_set = new LinkedHashSet<>(); 
        temp_set.addAll(input_list); 
        input_list.clear(); 
        input_list.addAll(temp_set); 
        System.out.println("\nThe list with no duplicates is: \n" + input_list); 
    } 
    
    public static void main(String[] args) { 
        System.out.println("The required packages have been imported"); 
        ArrayList input_list = new ArrayList<>(Arrays.asList(150, 250, 300, 250, 500, 150, 600, 750, 300)); 
        System.out.println("The list is defined as: " + input_list); 
        remove_duplicates(input_list); 
    } 
}

Kết quả

The required packages have been imported 
The list is defined as: [150, 250, 300, 250, 500, 150, 600, 750, 300] 
The list with no duplicates is: [150, 250, 300, 500, 600, 750]