Tải bản đầy đủ (.pptx) (13 trang)

Báo cáo lập trình java về Collecting Results

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (760.93 KB, 13 trang )

Trường Đại học Bách Khoa Hà Nội
Viện Công nghệ thông tin & Truyền thông
---------------------IT4784 – LẬP TRÌNH JAVA

Chương 2. The Stream API
S V: N g u y ễ n A n h Q u â n
M SS V: 2 0 1 2 2 2 7 6
Lớp: CNTT1 01 – K57
G V: T S . N g u y ễ n h ồ n g q u a n g
1


2.9 Collecting results – Thu thập kết quả

2


2.9 Collecting results

Thu thập dữ liệu vào mảng

 Sử dụng vòng lặp
 Phương thức stream.toArray()
 String[] result = words.toArray(String[]::new);
//words.toArray() trả về Object[]

3


2.9 Collecting results


Phương thức stream.collect()
 Đưa dữ liệu vào HashSet:
HashSet<String> result =
stream.collect(HashSet::new, HashSet::add, HashSet::addAll);

supplier

combiner
accumulator

4


2.9 Collecting results

Phương thức stream.collect()
 Đưa dữ liệu vào List hoặc Set:

List<String> result = stream.collect(Collectors.toList());
Set<String> result = stream.collect(Collectors.toSet());

 Đưa dữ liệu vào kiểu set khác:
TreeSet<String> result = stream.collect(Collectors.toCollection(TreeSet::new));

5


2.9 Collecting results

Liên kết các xâu từ stream

String result = stream.collect(Collectors.joining());

String result = stream.collect(Collectors.joining(", "));

String result = stream.map(Object::toString).collect(Collectors.joining(", "));

6


2.9 Collecting results

Tối giản stream
IntSummaryStatistics summary =
words.collect(Collectors.summarizingInt(String::length));
double averageWordLength = summary.getAverage();
double maxWordLength = summary.getMax();

7


2.9 Collecting results

Phương thức stream.forEach()
stream.forEach();
stream.forEachOrdered();
VD:

stream.forEach(System.out::println);

8



9


1) Sau khi gọi phương thức stream.toArray() thu được mảng kiểu gì?

A. Kiểu Byte
B. Kiểu Object
C. Trình dịch báo lỗi và yêu cầu người lập trình phải khai báo kiểu
D. Kiểu bất kỳ

10


2) Đối số HashSet::new trong đoạn code sau có ý nghĩa gì?
 
HashSet<String> result =
stream.collect(HashSet::new, HashSet::add, HashSet::addAll);

A. Là một combiner để tạo các phần tử mới của stream
B. Là một accumulator để tạo một thể hiện duy nhất của đối tượng đích
C. Là một supplier để tạo các thể hiện của đối tượng đích
D. Cả 3 phương án trên không đúng

11


3) Stream sẽ không sử dụng được nữa sau khi gọi các phương thức nào sau đây:


A. forEach() và forEachOrdered()

B. toArray() và toList()

C. joining() và getMax()

D. map() và collect()

12


Cảm ơn thầy giáo và các bạn!

13



×