ตัวอย่างโค้ด
import java.util.stream.*;
import java.util.*;
public class Demo {
public static Set setMerge(Set set1, Set set2) {
Set merged = set1.stream()
.collect(Collectors.toSet());
merged.addAll(set2);
return merged;
}
public static void main(String[] args) {
Set set1 = new HashSet<>(Arrays.asList(34, 67, 89, 102));
Set set2 = new HashSet<>(Arrays.asList(77, 11, 0, -33));
System.out.println("เซตแรก: " + set1);
System.out.println("เซตที่สอง: " + set2);
System.out.println("เซตที่รวมแล้ว: " + setMerge(set1, set2));
}
}
ผลลัพธ์
เซตแรก: [34, 67, 102, 89] เซตที่สอง: [0, -33, 11, 77] เซตที่รวมแล้ว: [0, -33, 34, 67, 102, 89, 11, 77]
คำอธิบาย
เมธอด setMerge ใช้ Stream API และ Collectors.toSet() สร้างเซตใหม่จาก set1 แล้วใช้ addAll รวมสมาชิกจาก set2 เข้าไป
เนื่องจากเป็น Set ค่าที่ซ้ำกันจะถูกกำจัดอัตโนมัติ (แต่ในตัวอย่างไม่มีค่าซ้ำ)
วิธีอื่นๆ ในการรวม Set
1. ใช้ Stream.concat (Java 8+)
public staticSet mergeWithConcat(Set s1, Set s2) { return Stream.concat(s1.stream(), s2.stream()) .collect(Collectors.toSet()); }
2. ใช้ addAll โดยตรง (แก้ไข set1 ตรงๆ)
set1.addAll(set2); // set1 จะเปลี่ยนไป (mutate) // หากไม่ต้องการแก้ไขต้นฉบับ: Setcopy = new HashSet<>(set1); copy.addAll(set2);
3. ใช้ Guava Sets.union (ไลบรารีภายนอก)
Setunion = Sets.union(set1, set2); // View - ไม่สร้างเซตใหม่จริงๆ
ประสิทธิภาพ
| วิธี | Time Complexity | Space | Mutate Original? |
|---|---|---|---|
| addAll | O(n) | O(1) เพิ่ม | ใช่ |
| Stream.concat + collect | O(n+m) | O(n+m) | ไม่ |
| Guava union | O(1) lazy | O(1) | ไม่ (view) |
ข้อสังเกต
- ใช้
HashSetได้ O(1) ต่อการ insert/lookup - หากต้องการรักษาลำดับ ใช้
LinkedHashSet - หากต้องการเรียงลำดับ ใช้
TreeSet