![Berhenti menulis loop! 10 praktik terbaik teratas untuk bekerja dengan koleksi di Java 8 - 1]()
Seperti yang Anda ketahui, kebiasaan kita adalah sifat kedua. Dan begitu Anda terbiasa menulis
for (int i = 0; i <......)
, tidak ada bagian dari Anda yang ingin mempelajari kembali konstruksi ini (terutama karena ini cukup sederhana dan mudah dipahami). Namun, loop sering digunakan berulang kali untuk melakukan operasi dasar yang sama, dan pengulangan adalah sesuatu yang sangat ingin kami singkirkan. Dengan Java 8, Oracle telah memutuskan untuk membantu kami melakukan ini. Di bawah ini adalah 10 metode pengumpulan terbaik yang akan menghemat banyak waktu dan kode.
1. Iterable.forEach(Konsumen <? Super T> tindakan)
Nama berbicara untuk dirinya sendiri. Itu mengulangi koleksi yang diteruskan sebagai argumen, dan mengeksekusi ekspresi tindakan lambda untuk setiap elemennya.
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. Collection.removeIf(Predikat<? super E> filter)
Sekali lagi, tidak ada yang sulit di sini. Metode ini mengulang koleksi dan menghapus semua elemen yang cocok dengan
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 + " "));
Dalam satu baris, kami menghapus dari daftar semua angka yang lebih besar dari 5.
3. Map.forEach(tindakan BiConsumer <? super K, ? super V>)
Metode ini
forEach
bekerja tidak hanya untuk kelas yang mengimplementasikan antarmuka
Collection
, tetapi juga untuk
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 (tombol K, BiFunction<? Super K,? Super V,? Extends V> remappingFunction)
Terlihat sedikit lebih mengintimidasi, tetapi sebenarnya sederhana, seperti yang sebelumnya. Metode ini menetapkan
key
nilai sama dengan hasil eksekusi
mappingFunction
. Misalnya:
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
Penulis "Thinking in Java" pasti keren! :)
5. Map.computeIfAbsent(K kunci, Fungsi <? super K, ? meluas V> mappingFunction)
Metode ini akan menambahkan elemen baru ke
Map
, tetapi hanya jika belum memiliki elemen dengan kunci tersebut. Nilai yang ditetapkan akan menjadi hasil dari eksekusi
mappingFunction
. Jika elemen dengan kunci sudah ada, itu tidak akan ditimpa. Itu hanya akan tetap apa adanya. Mari kembali ke buku kita dan coba metode baru:
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));
Inilah kami
mappingFunction
:
public static String getHarryPotterAuthor() {
return "Joanne Rowling";
}
Dan inilah buku barunya:
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 kunci, BiFunction<? super K, ? super V, ? meluas V> remappingFunction)
Di sini kita memiliki prinsip yang sama dengan
Map.compute()
, tetapi perhitungan dilakukan hanya jika item dengan
key
sudah ada.
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));
Panggilan pertama ke fungsi tersebut tidak membuat perubahan, karena tidak ada buku berjudul "Eugene Onegin" di
Map
. Namun pada panggilan kedua, program tersebut mengubah penulis buku "The Brothers Karamazov" menjadi Alexander Pushkin. Keluaran:
_________________
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(Kunci objek, V defaultValue)
Metode ini mengembalikan nilai yang sesuai dengan
key
. Jika kunci tidak ada, maka mengembalikan nilai default.
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);
Ini sangat nyaman:
Unknown author
8. Map.merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
Saya bahkan tidak repot-repot mencoba menghitung berapa banyak baris kode yang akan dihemat oleh metode ini.
- Jika
key
tidak ada di Map
, atau jika value
untuk kunci ini adalah null
, maka metode menambahkan key-value
pasangan yang diteruskan ke Map
.
- Jika
key
memang ada dan nya value != null
, maka metode tersebut mengubah nilainya menjadi hasil eksekusi remappingFunction
.
- Jika
remappingFunction
return null
, maka key
dihapus dari koleksi.
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));
Keluaran:
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
*maaf, Bruce*
9. Peta.putIfAbsent(K kunci, nilai V)
Sebelumnya, untuk menambahkan pasangan ke a
Map
, jika belum ada, Anda harus melakukan hal berikut:
Map <String, String> map = new HashMap<>();
if (map.get("Lord of the Rings") == null)
map.put("Lord of the Rings", "John Tolkien");
Sekarang semuanya menjadi lebih mudah:
Map<String, String> map = new HashMap<>();
map.putIfAbsent("Lord of the Rings", "John Tolkien");
10. Map.replace dan Map.replaceAll()
Terakhir, tetapi tidak kalah penting.
Map.replace(K key, V newValue)
ganti key
nilainya dengan newValue
, jika ada kunci seperti itu. Jika tidak, tidak ada yang terjadi.
Map.replace(K key, V oldValue, V newValue)
melakukan hal yang sama, tetapi hanya jika nilai saat ini key
sama dengan oldValue
.
Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)
mengganti masing-masing value
dengan hasil fungsi.
Misalnya:
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
Itu tidak berhasil! Nilai saat ini untuk kunci "The Brothers Karamazov" adalah "Fyodor Dostoevsky", bukan "Bruce Eckel", jadi tidak ada yang berubah.
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
Kami dengan mudah mengubah nilai keseluruhan
Map
tanpa konstruksi yang rumit! PS Membiasakan diri dengan yang baru selalu sulit, tetapi perubahan ini sangat bagus. Bagaimanapun, beberapa bagian dari kode saya pasti kurang seperti spageti dari sebelumnya :) Semoga berhasil dalam belajar!
GO TO FULL VERSION