การกรองและนับอีเมลเพื่อการมีส่วนร่วมของลูกค้า
ทีมการตลาดต้องการนับจำนวนลูกค้าที่ใช้อีเมลของบริษัท (อีเมลที่ลงท้ายด้วย @company.com) เพื่อส่งโปรโมชันให้กับลูกค้ากลุ่มนั้น Stream ช่วยให้กรองและนับอีเมลเหล่านี้ได้อย่างมีประสิทธิภาพ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Input/Output และ Streams ใน Java
คำแนะนำการฝึกหัด
- แปลงลิสต์
emailsให้เป็นออบเจกต์Stream - กรองเฉพาะอีเมลที่ลงท้ายด้วย
@company.com - นับจำนวนอีเมลที่ตรงเงื่อนไข
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class CompanyEmailFilter {
public static void main(String[] args) {
List emails = new ArrayList<>();
emails.add("[email protected]");
emails.add("[email protected]");
emails.add("[email protected]");
emails.add("[email protected]");
// Convert list to Stream
Stream stream = emails.____();
long count = stream
// Filter email ends with "@company.com"
.____(email -> email.endsWith("@company.com"))
// Count matching emails
.____();
System.out.println("Total company emails: " + count);
}
}