Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Java Program รวม (Merge) สอง List

การ Merge (รวม) สอง List ใน Java

Merge คือการนำสมาชิกจาก List หลาย List มารวมเป็น List เดียว สามารถทำได้หลายวิธี

วิธีที่ 1: addAll() - มาตรฐานง่ายที่สุด

List list1 = new ArrayList<>(Arrays.asList(45, 60, 95));
List list2 = new ArrayList<>(Arrays.asList(105, 120));

List merged = new ArrayList<>(list1); // Copy list1
merged.addAll(list2); // เพิ่ม list2 ต่อท้าย
// [45, 60, 95, 105, 120]

ตัวอย่างที่ 1: ใน main โดยตรง

import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List list1 = new ArrayList<>();
        list1.add(45);
        list1.add(60);
        list1.add(95);
        System.out.println("The first list is defined as: " + list1);
        
        List list2 = new ArrayList<>();
        list2.add(105);
        list2.add(120);
        System.out.println("The second list is defined as: " + list2);
        
        List resultList = new ArrayList<>();
        resultList.addAll(list1);
        resultList.addAll(list2);
        
        System.out.println("\nThe list after merging the two lists: " + resultList);
    }
}

ผลลัพธ์

The first list is defined as: [45, 60, 95]
The second list is defined as: [105, 120]
The list after merging the two lists: [45, 60, 95, 105, 120]

ตัวอย่างที่ 2: แยกเป็นเมธอด (OOP)

import java.util.ArrayList;
import java.util.List;

public class Demo {
    
    static void merge(List list1, List list2) {
        List result = new ArrayList<>();
        result.addAll(list1);
        result.addAll(list2);
        System.out.println("\nThe list after merging the two lists: " + result);
    }
    
    public static void main(String[] args) {
        List list1 = new ArrayList<>(Arrays.asList(45, 60, 95));
        List list2 = new ArrayList<>(Arrays.asList(105, 120));
        
        System.out.println("The first list is defined as: " + list1);
        System.out.println("The second list is defined as: " + list2);
        
        merge(list1, list2);
    }
}

วิธีอื่นๆ (Modern Java)

1. Stream API (Java 8+)

// concat + collect
List merged = Stream.concat(list1.stream(), list2.stream())
    .collect(Collectors.toList());

// หรือ flatMap
List merged2 = Stream.of(list1, list2)
    .flatMap(List::stream)
    .collect(Collectors.toList());

2. Java 10+ var + copyOf

var merged = new ArrayList<>(list1);
merged.addAll(list2);

// หรือ
var merged = new ArrayList<>(List.copyOf(list1));
merged.addAll(list2);

3. Apache Commons Collections

// ListUtils.union (Unique - ลบซ้ำ)
List union = ListUtils.union(list1, list2);

// ListUtils.sum (Keep duplicates - concatenate)
List concatenated = ListUtils.sum(list1, list2);

Merge แบบ Unique (Union - ไม่ซ้ำ)

// ใช้ LinkedHashSet รักษาลำดับ
Set set = new LinkedHashSet<>();
set.addAll(list1);
set.addAll(list2);
List uniqueMerged = new ArrayList<>(set);

// หรือ Stream distinct
List uniqueMerged = Stream.concat(list1.stream(), list2.stream())
    .distinct()
    .collect(Collectors.toList());

Merge หลาย List (Multiple Lists)

List> lists = Arrays.asList(list1, list2, list3, list4);

// Stream flatMap
List merged = lists.stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());

// Loop แบบเดิม
List merged = new ArrayList<>();
for (List list : lists) {
    merged.addAll(list);
}

Merge Sorted Lists (Merge Algorithm - O(n+m))

ถ้าทั้งสอง List เรียงแล้ว สามารถ Merge ได้ O(n+m) แทนที่จะรวมแล้ว Sort O((n+m) log(n+m))

public static List mergeSorted(List a, List b) {
    List result = new ArrayList<>();
    int i = 0, j = 0;
    
    while (i < a.size() && j < b.size()) {
        if (a.get(i) <= b.get(j)) {
            result.add(a.get(i++));
        } else {
            result.add(b.get(j++));
        }
    }
    
    while (i < a.size()) result.add(a.get(i++));
    while (j < b.size()) result.add(b.get(j++));
    
    return result;
}

// ใช้งาน
List a = Arrays.asList(1, 3, 5, 7);
List b = Arrays.asList(2, 4, 6, 8);
List merged = mergeSorted(a, b); // [1,2,3,4,5,6,7,8]

Performance Comparison

Method Time Space Note
addAll (ArrayList) O(n+m) O(n+m) Standard, Fast
Stream concat O(n+m) O(n+m) Functional, Lazy
Manual Loop O(n+m) O(n+m) Control เต็มที่
Merge Sorted O(n+m) O(n+m) Optimal สำหรับ Sorted Input

สรุป

  • addAll() = วิธีมาตรฐาน เร็ว สะดวก
  • Stream.concat() = Functional Style, Lazy Evaluation
  • ต้องการ Unique → ใช้ LinkedHashSet หรือ Stream.distinct()
  • Sorted Lists → ใช้ Merge Algorithm (Two Pointers) O(n+m)
  • หลาย Lists → Stream.of(lists).flatMap(List::stream)