Input/Output และ Streams ใน Java
Alex Liu
Software Development Engineer
การแปลงข้อมูลด้วย streams
List เป็น Set)ArrayList, LinkedList)HashSet, TreeSet)Keys/Values เป็น Streams) (เช่น HashMap, TreeMap)Arrays.stream())ตัวอย่าง ArrayList ชื่อ names สำหรับใช้ตลอดวิดีโอนี้
names: ["Alice", "Bob", "Charlie", "David"]
Set, Collectors และ Stream ที่จำเป็นimport java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream;// Convert the `ArrayList` we created earlier `names` to a `Stream` Stream<String> namesStream = names.stream();
[Alice, Bob, Charlie, David]// Use `.map()` to convert each element to upper case
Stream<String> upperCaseNameStream = namesStream.map(
name -> name.toUpperCase())
[ALICE, BOB, CHARLIE, DAVID]// use `.collect()` and `Collectors.toSet()` to store the transformed stream data
upperCaseNameStream.collect(Collectors.toSet())
{CHARLIE, ALICE, BOB, DAVID}
เมธอด .reduce()
.reduce() รับค่าอินพุต 2 ตัว
0(x, y) -> x + y หมายความว่า:x แทนค่าสะสมที่ได้จนถึงขณะนั้นy แทนข้อมูลตัวปัจจุบันที่กำลังประมวลผลy เข้ากับ x ไปเรื่อย ๆ จนครบทุกตัวArrayList ชื่อ names ให้เป็น Stream objectStream<String> stream = names.stream();
.map() แปลงชื่อเป็นความยาว แล้วใช้ .reduce() รวมค่าทั้งหมดstream
.map(name -> name.length())
.reduce(0, (sum, length) -> sum + length);
20Input/Output และ Streams ใน Java