Nhập/Xuất và Streams trong Java
Alex Liu
Software Development Engineer
Chuyển đổi dữ liệu với streams
List sang Set)ArrayList, LinkedList)HashSet, TreeSet)Keys/Values là Streams) (vd: HashMap, TreeMap)Arrays.stream())Ví dụ ArrayList tên names dùng cho phần còn lại của video
names: ["Alice", "Bob", "Charlie", "David"]
Set, Collectors và Streamimport 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}
Phương thức .reduce()
Dùng .reduce() với hai đầu vào
0(x, y) -> x + y nghĩa là:x là tổng đã tích lũyy là phần tử hiện tạiy vào x cho đến khi xử lý hếtArrayList names thành một đối tượng Stream.Stream<String> stream = names.stream();
.map() để lấy độ dài tên và .reduce() để cộng lạistream
.map(name -> name.length())
.reduce(0, (sum, length) -> sum + length);
20Nhập/Xuất và Streams trong Java