CodeGym /Blog Jawa /Acak /Stop nulis loops! 10 praktik paling apik kanggo nggarap k...
John Squirrels
tingkat
San Francisco

Stop nulis loops! 10 praktik paling apik kanggo nggarap koleksi ing Jawa 8

Diterbitake ing grup
Stop nulis loops!  10 praktik paling apik kanggo nggarap koleksi ing Jawa 8 - 1 Kaya sing wis dingerteni, kebiasaan kita minangka sifat kapindho. Lan yen sampeyan wis biasa nulis for (int i = 0; i <......), ora ana bagean saka sampeyan sing pengin sinau maneh konstruksi iki (utamane amarga cukup prasaja lan bisa dingerteni). Nanging, puteran asring bola-bali digunakake kanggo nindakake operasi dhasar sing padha, lan pengulangan minangka perkara sing pengin kita nyingkirake. Kanthi Java 8, Oracle mutusake kanggo mbantu kita nindakake iki. Ing ngisor iki ana 10 cara koleksi paling apik sing bakal ngirit wektu lan kode.

1. Iterable.forEach(Consumer <? Super T> action)

Jeneng ngandika kanggo dhewe. Iku iterates liwat koleksi liwati minangka argumen, lan nglakokaké expression lambda tumindak kanggo saben unsur sawijining.

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(Predicate<? super E> filter)

Maneh, ora ana sing angel ing kene. Cara kasebut ngulang koleksi lan mbusak unsur sing cocog 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 + " "));
Ing baris siji, kita mbusak saka dhaptar kabeh nomer luwih saka 5.

3. Map.forEach(BiConsumer <? super K, ? super V> action)

Cara kasebut forEachora mung dianggo kanggo kelas sing ngetrapake antarmuka Collection, nanging uga kanggo 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)

Katon rada medeni, nanging nyatane prasaja, kaya kabeh sing sadurunge. Cara iki nyetel keynilai sing padha karo asil eksekusi mappingFunction. Tuladhane:

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
Pengarang "Thinking in Java" mesthi keren! :)

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

Cara iki bakal nambah unsur anyar menyang Map, nanging mung yen durung duwe unsur karo tombol sing. Nilai sing ditugasake bakal dadi asil saka eksekusi mappingFunction. Yen unsur karo tombol wis ana, iku ora bakal ditindhes. Iku mung bakal tetep kaya. Ayo bali menyang buku lan coba cara anyar:

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));
Punika kita mappingFunction:

public static String getHarryPotterAuthor() {
        return "Joanne Rowling";
    }
Lan iki buku anyar:

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(tombol K, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Ing kene kita duwe prinsip sing padha karo Map.compute(), nanging petungan ditindakake mung yen item sing keywis ana.

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));
Telpon pisanan kanggo fungsi ora owah-owahan, amarga ora ana buku kanthi irah-irahan "Eugene Onegin" ing kita Map. Nanging ing telpon kapindho, program diganti penulis buku "The Brothers Karamazov" kanggo Alexander Pushkin. Output:

_________________
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(tombol obyek, V defaultValue)

Cara iki ngasilake nilai sing cocog karo key. Yen tombol ora ana, banjur bakal ngasilake nilai standar.

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);
Iki trep banget:

Unknown author

8. Map.merge(K kunci, nilai V, BiFunction<? super V, ? super V, ? ngluwihi V> remappingFunction)

Aku malah ora keganggu nyoba kanggo ngetung carane akeh baris kode cara iki bakal nyimpen sampeyan.
  1. Yen keyora ana ing Panjenengan Map, utawa yen valuekanggo tombol iki null, banjur cara nambahake key-valuepasangan liwati menyang Map.
  2. Yen keyana lan value != null, banjur metode kasebut ngganti nilai dadi asil eksekusi remappingFunction.
  3. Yen remappingFunctionbali null, banjur keydibusak saka 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));
Output:

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
*ngapunten, Bruce*

9. Map.putIfAbsent(K kunci, nilai V)

Sadurunge, kanggo nambah pasangan menyang Map, yen durung ana, sampeyan kudu nindakake ing ngisor iki:

Map <String, String> map = new HashMap<>();
if (map.get("Lord of the Rings") == null)
    map.put("Lord of the Rings", "John Tolkien");
Saiki kabeh wis dadi luwih gampang:

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

10. Map.replace lan Map.replaceAll()

Pungkasan nanging paling ora.
  1. Map.replace(K key, V newValue)ngganteni keynilai karo newValue, yen tombol kuwi ana. Yen ora, ora ana sing kedadeyan.
  2. Map.replace(K key, V oldValue, V newValue)nindakake perkara sing padha, nanging mung yen nilai saiki kanggo keypadha karo oldValue.
  3. Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)ngganti saben valuekaro asil saka fungsi.
Tuladhane:

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
Ora bisa! Nilai saiki kanggo tombol "The Brothers Karamazov" yaiku "Fyodor Dostoevsky", dudu "Bruce Eckel", mula ora ana sing owah.

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
Kita gampang ngganti nilai kanggo kabeh Maptanpa konstruksi rumit! PS Biasane sing anyar mesthi angel, nanging owah-owahan kasebut pancen apik. Ing acara apa wae, sawetara bagéan saka kode sandi mesthi kurang kaya spageti tinimbang sadurunge :) Good luck ing sinau!
Komentar
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION