CodeGym /Blog Java /Ngẫu nhiên /Ngừng viết vòng lặp! 10 phương pháp hay nhất để làm việc ...
John Squirrels
Mức độ
San Francisco

Ngừng viết vòng lặp! 10 phương pháp hay nhất để làm việc với các bộ sưu tập trong Java 8

Xuất bản trong nhóm
Ngừng viết vòng lặp!  10 phương pháp hay nhất để làm việc với các bộ sưu tập trong Java 8 - 1 Như bạn đã biết, thói quen của chúng ta là bản chất thứ hai. Và một khi bạn đã quen viết for (int i = 0; i <......), không phần nào trong bạn muốn học lại cấu trúc này (đặc biệt là vì nó khá đơn giản và dễ hiểu). Tuy nhiên, các vòng lặp thường được sử dụng lặp đi lặp lại để thực hiện các thao tác cơ bản giống nhau và sự lặp lại là điều mà chúng tôi rất muốn loại bỏ. Với Java 8, Oracle đã quyết định giúp chúng tôi làm điều này. Dưới đây là 10 phương pháp thu thập tốt nhất sẽ giúp bạn tiết kiệm rất nhiều thời gian và mã.

1. Iterable.forEach(Hành động <? Super T> của người tiêu dùng)

Tên nói cho chính nó. Nó lặp lại bộ sưu tập được truyền dưới dạng đối số và thực thi biểu thức lambda hành động cho từng phần tử của nó.

List <Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
 numbers.forEach(s -> System.out.print(s + " "));

1 2 3 4 5 6 7

2. Bộ sưu tập.removeIf(Bộ lọc vị ngữ<? super E>)

Một lần nữa, không có gì khó khăn ở đây. Phương thức lặp qua bộ sưu tập và loại bỏ bất kỳ phần tử nào khớp với filter.

 List <Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
 numbers.removeIf(s -> s > 5);
 numbers.forEach(s -> System.out.print(s + " "));
Trong một dòng, chúng tôi đang xóa khỏi danh sách tất cả các số lớn hơn 5.

3. Map.forEach(Hành động BiConsumer <? super K, ? super V>)

Phương thức này forEachkhông chỉ hoạt động đối với các lớp triển khai Collectiongiao diện mà còn đối với các lớp Map.

 Map <String, String> books = new HashMap<>();
 books.put("War and Peace", "Leo Tolstoy");
 books.put("Crime and Punishment", "Fyodor Dostoevsky");
 books.put("Thinking in Java", "Bruce Eckel");
 books.put("The Brothers Karamazov", "Fyodor Dostoevsky");
 books.put("The Lord of the Rings", "John Tolkien");
 books.forEach((a,b) -> System.out.println("Book title: " + a + ". Author: "+ b));

Book title: The Brothers Karamazov. Author: Fyodor Dostoevsky
Book title: Thinking in Java. Author: Bruce Eckel
Book title: Crime and Punishment. Author: Fyodor Dostoevsky
Book title: War and Peace. Author: Leo Tolstoy
Book title: Lord of the Rings. Author: John Tolkien

4. Map.compute (K key, BiFunction<?Super K,?Super V,?Extends V> remappingFunction)

Trông có vẻ đáng sợ hơn một chút, nhưng thực tế thì đơn giản, giống như tất cả những cái trước đó. Phương thức này đặt keygiá trị của bằng với kết quả của việc thực hiện mappingFunction. Ví dụ:

Map <String, String> books = new HashMap<>();
books.put("War and Peace", "Leo Tolstoy");
books.put("Crime and Punishment", "Fyodor Dostoevsky");
books.put("Thinking in Java", "Bruce Eckel");
books.put("The Brothers Karamazov", "Fyodor Dostoevsky");
books.put("The Lord of the Rings", "John Tolkien");
books.forEach((a,b) -> System.out.println("Book title: " + a + ". Author: "+ b));
 
books.compute("Thinking in Java", (a,b) -> b + ", cool dude");
System.out.println("_______________________");
books.forEach((a,b) -> System.out.println("Book title: " + a + ". Author: "+ b));

Book title: The Brothers Karamazov. Author: Fyodor Dostoevsky
Book title: Thinking in Java. Author: Bruce Eckel
Book title: Crime and Punishment. Author: Fyodor Dostoevsky
Book title: War and Peace. Author: Leo Tolstoy
Book title: Lord of the Rings. Author: John Tolkien
_______________________
Book title: The Brothers Karamazov. Author: Fyodor Dostoevsky
Book title: Thinking in Java. Author: Bruce Eckel, cool dude
Book title: Crime and Punishment. Author: Fyodor Dostoevsky
Book title: War and Peace. Author: Leo Tolstoy
Book title: Lord of the Rings. Author: John Tolkien
Tác giả của "Suy nghĩ bằng Java" chắc chắn là tuyệt vời! :)

5. Map.computeIfAbsent(K key, Function <? super K, ? extends V> mappingFunction)

Phương thức này sẽ thêm một phần tử mới vào Map, nhưng chỉ khi nó chưa có phần tử với khóa đó. Giá trị được gán sẽ là kết quả của việc thực thi lệnh mappingFunction. Nếu một phần tử có khóa đã tồn tại, nó sẽ không bị ghi đè. Nó sẽ đơn giản vẫn như cũ. Hãy quay lại với những cuốn sách của chúng ta và thử một phương pháp mới:

Map <String, String> books = new HashMap<>();
books.put("War and Peace", "Leo Tolstoy");
books.put("Crime and Punishment", "Fyodor Dostoevsky");
books.put("Thinking in Java", "Bruce Eckel");
books.put("The Brothers Karamazov", "Fyodor Dostoevsky");
books.put("The Lord of the Rings", "John Tolkien");
 
books.computeIfAbsent("Harry Potter and the Prisoner of Azkaban", b -> getHarryPotterAuthor());
books.forEach((a,b) -> System.out.println("Book title: " + a + ". Author: "+ b));
Đây là của chúng tôi mappingFunction:

public static String getHarryPotterAuthor() {
        return "Joanne Rowling";
    }
Và đây là cuốn sách mới:

Book title: The Brothers Karamazov. Author: Fyodor Dostoevsky
Book title: Thinking in Java. Author: Bruce Eckel
Book title: Crime and Punishment. Author: Fyodor Dostoevsky
Book title: War and Peace. Author: Leo Tolstoy
Book title: Harry Potter and the Prisoner of Azkaban. Author: Joanne Rowling
Book title: Lord of the Rings. Author: John Tolkien

6. Map.computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Ở đây chúng ta có nguyên tắc tương tự như Map.compute(), nhưng các tính toán chỉ được thực hiện nếu một mục keyđã tồn tại.

Map <String, String> books = new HashMap<>();
books.put("War and Peace", "Leo Tolstoy");
books.put("Crime and Punishment", "Fyodor Dostoevsky");
books.put("Thinking in Java", "Bruce Eckel");
books.put("The Brothers Karamazov", "Fyodor Dostoevsky");
books.put("The Lord of the Rings", "John Tolkien");
 
books.computeIfPresent("Eugene Onegin", (a,b) -> b = "Alexander Pushkin");
System.out.println("_________________");
books.forEach((a,b) -> System.out.println("Book title: " + a + ". Author: "+ b));
books.computeIfPresent("The Brothers Karamazov", (a,b) -> b = "Alexander Pushkin");
System.out.println("_________________");
books.forEach((a,b) -> System.out.println("Book title: " + a + ". Author: "+ b));
Lần gọi hàm đầu tiên không có thay đổi nào, bởi vì không có cuốn sách nào có tựa đề "Eugene Onegin" trong Map. Nhưng trong cuộc gọi thứ hai, chương trình đã thay đổi tác giả của cuốn sách "Anh em nhà Karamazov" thành Alexander Pushkin. Đầu ra:

_________________
Book title: The Brothers Karamazov. Author: Fyodor Dostoevsky
Book title: Thinking in Java. Author: Bruce Eckel
Book title: Crime and Punishment. Author: Fyodor Dostoevsky
Book title: War and Peace. Author: Leo Tolstoy
Book title: Lord of the Rings. Author: John Tolkien
 _________________
Book title: The Brothers Karamazov. Author: Alexander Pushkin
Book title: Thinking in Java. Author: Bruce Eckel
Book title: Crime and Punishment. Author: Fyodor Dostoevsky
Book title: War and Peace. Author: Leo Tolstoy
Book title: Lord of the Rings. Author: John Tolkien

7. Map.getOrDefault(Khóa đối tượng, V defaultValue)

Phương thức này trả về giá trị tương ứng với key. Nếu khóa không tồn tại, thì nó sẽ trả về giá trị mặc định.

Map <String, String> books = new HashMap<>();
books.put("War and Peace", "Leo Tolstoy");
books.put("Crime and Punishment", "Fyodor Dostoevsky");
books.put("Thinking in Java", "Bruce Eckel");
books.put("The Brothers Karamazov", "Fyodor Dostoevsky");
books.put("The Lord of the Rings", "John Tolkien");
 
String igor = books.getOrDefault("The Tale of Igor's Campaign", "Unknown author");
System.out.println(igor);
Điều này rất thuận tiện:

Unknown author

8. Map.merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

Tôi thậm chí không bận tâm đến việc tính xem phương pháp này sẽ giúp bạn tiết kiệm được bao nhiêu dòng mã.
  1. Nếu keykhông tồn tại trong khóa của bạn Maphoặc nếu valuekhóa này có null, thì phương thức này sẽ thêm key-valuecặp đã truyền vào tệp Map.
  2. Nếu keytồn tại và giá trị của nó value != null, thì phương thức sẽ thay đổi giá trị của nó thành kết quả của việc thực thi remappingFunction.
  3. Nếu remappingFunctiontrả về null, sau đó keybị xóa khỏi bộ sưu tập.

Map <String, String> books = new HashMap<>();
books.put("War and Peace", "Leo Tolstoy");
books.put("Crime and Punishment", "Fyodor Dostoevsky");
books.put("Thinking in Java", "Bruce Eckel");
books.put("The Brothers Karamazov", "Fyodor Dostoevsky");
books.put("The Lord of the Rings", "John Tolkien");
 
books.merge("Thinking in Java", "Bruce Eckel", (a, b) -> b + " and some coauthor");
books.forEach((a, b) -> System.out.println("Title: " + a + ". Author: "+ b));
Đầu ra:

Title: The Brothers Karamazov. Author: Fyodor Dostoevsky
Title: Thinking in Java. Author: Bruce Eckel and some coauthor
Title: Crime and Punishment. Author: Fyodor Dostoevsky
Title: War and Peace. Author: Leo Tolstoy
Title: Lord of the Rings. Author: John Tolkien
*xin lỗi, Bruce*

9. Map.putIfAbsent(Khóa, giá trị V)

Trước đây, để thêm một cặp vào một Map, nếu nó chưa có ở đó, bạn phải làm như sau:

Map <String, String> map = new HashMap<>();
if (map.get("Lord of the Rings") == null)
    map.put("Lord of the Rings", "John Tolkien");
Bây giờ mọi thứ đã trở nên dễ dàng hơn nhiều:

Map<String, String> map = new HashMap<>();
map.putIfAbsent("Lord of the Rings", "John Tolkien");

10. Map.replace và Map.replaceAll()

Cuối cùng nhưng không kém phần quan trọng.
  1. Map.replace(K key, V newValue)thay thế keygiá trị của bằng newValue, nếu khóa đó tồn tại. Nếu không, không có gì xảy ra.
  2. Map.replace(K key, V oldValue, V newValue)làm điều tương tự, nhưng chỉ khi giá trị hiện tại cho keybằng oldValue.
  3. Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)thay thế từng cái valuebằng kết quả của hàm.
Ví dụ:

Map <String, String> books = new HashMap<>();
books.put("War and Peace", "Leo Tolstoy");
books.put("Crime and Punishment", "Fyodor Dostoevsky");
books.put("Thinking in Java", "Bruce Eckel");
books.put("The Brothers Karamazov", "Fyodor Dostoevsky");
books.put("The Lord of the Rings", "John Tolkien");
 
books.replace("The Brothers Karamazov", "Bruce Eckel", "John Tolkien");
books.forEach((a, b) -> System.out.println("Title: " + a + ". Author: "+ b));

Title: The Brothers Karamazov. Author: Fyodor Dostoevsky
Title: Thinking in Java. Author: Bruce Eckel
Title: Crime and Punishment. Author: Fyodor Dostoevsky
Title: War and Peace. Author: Leo Tolstoy
Title: Lord of the Rings. Author: John Tolkien
Nó không hoạt động! Giá trị hiện tại của khóa "Anh em nhà Karamazov" là "Fyodor Dostoevsky", không phải "Bruce Eckel", vì vậy không có gì thay đổi.

Map  books = new HashMap<>();
books.put("War and Peace", "Leo Tolstoy");
books.put("Crime and Punishment", "Fyodor Dostoevsky");
books.put("Thinking in Java", "Bruce Eckel");
books.put("The Brothers Karamazov", "Fyodor Dostoevsky");
books.put("The Lord of the Rings", "John Tolkien");
 
books.replaceAll((a,b) -> getCoolAuthor());
books.forEach((a, b) -> System.out.println("Title: " + a + ". Author: "+ b));

public static String getCoolAuthor() {
        return "Cool author";
     }

Title: The Brothers Karamazov. Author: Cool author
Title: Thinking in Java. Author: Cool author
Title: Crime and Punishment. Author: Cool author
Title: War and Peace. Author: Cool author
Title: Lord of the Rings. Author: Cool author
Chúng tôi dễ dàng thay đổi các giá trị cho toàn bộ Mapmà không cần bất kỳ cấu trúc phức tạp nào! PS Làm quen với cái mới luôn khó khăn, nhưng những thay đổi này thực sự tốt. Trong mọi trường hợp, một số phần trong mã của tôi chắc chắn ít giống spaghetti hơn trước :) Chúc bạn học tốt!
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION