CodeGym/Blog Java/Aleatoriu/Nu mai scrie bucle! Top 10 cele mai bune practici pentru ...
John Squirrels
Nivel
San Francisco

Nu mai scrie bucle! Top 10 cele mai bune practici pentru lucrul cu colecții în Java 8

Publicat în grup
Nu mai scrie bucle!  Top 10 cele mai bune practici pentru lucrul cu colecții în Java 8 - 1 După cum știți, obiceiurile noastre sunt a doua natură. Și odată ce te obișnuiești cu scrisul for (int i = 0; i <......), nicio parte din tine nu vrea să fie nevoită să reînvețe acest construct (mai ales că este destul de simplu și de înțeles). Cu toate acestea, buclele sunt adesea folosite în mod repetat pentru a efectua aceleași operațiuni de bază, iar repetarea este ceva de care am dori foarte mult să scăpăm. Cu Java 8, Oracle a decis să ne ajute să facem acest lucru. Mai jos sunt cele mai bune 10 metode de colectare care vă vor economisi o mulțime de timp și cod.

1. Iterable.forEach (acțiunea consumatorului <? Super T>)

Numele vorbește de la sine. Iterează peste colecția transmisă ca argument și execută expresia lambda de acțiune pentru fiecare dintre elementele sale.
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(filtru Predicate<? super E>)

Din nou, nimic greu aici. Metoda iterează peste colecție și elimină orice elemente care se potrivesc cu 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 + " "));
Într-o singură linie, eliminăm din listă toate numerele mai mari de 5.

3. Map.forEach (acțiune BiConsumer <? super K, ? super V>)

Metoda forEachfuncționează nu numai pentru clasele care implementează interfața Collection, ci și pentru 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 (tasta K, BiFunction<? Super K,? Super V,? Extends V> remappingFunction)

Pare puțin mai intimidant, dar de fapt simplu, ca toate cele anterioare. Această metodă setează keyvaloarea egală cu rezultatul executării mappingFunction. De exemplu:
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
Autorul cărții „Gândirea în Java” este cu siguranță cool! :)

5. Map.computeIfAbsent (tasta K, Funcția <? super K, ? extinde V> mappingFunction)

Această metodă va adăuga un nou element la Map, dar numai dacă nu are deja un element cu acea cheie. Valoarea atribuită va fi rezultatul executării mappingFunction. Dacă un element cu cheia există deja, acesta nu va fi suprascris. Pur și simplu va rămâne așa cum este. Să revenim la cărțile noastre și să încercăm o nouă metodă:
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));
Iată noastre mappingFunction:
public static String getHarryPotterAuthor() {
        return "Joanne Rowling";
    }
Și iată noua carte:
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 (tasta K, BiFunction<? super K, ? super V, ? extins V> remappingFunction)

Aici avem același principiu ca și Map.compute(), dar calculele sunt efectuate numai dacă un articol cu key​​există deja.
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));
Primul apel la funcție nu a adus modificări, deoarece nu există nicio carte intitulată „Eugene Onegin” în Map. Dar, în al doilea apel, programul l-a schimbat pe autorul cărții „Frații Karamazov” în Alexandru Pușkin. Ieșire:
_________________
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 (cheia obiectului, V defaultValue)

Această metodă returnează valoarea corespunzătoare key. Dacă cheia nu există, atunci returnează valoarea implicită.
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);
Acest lucru este foarte convenabil:
Unknown author

8. Map.merge (tasta K, valoarea V, BiFunction<? super V, ? super V, ? extins V> remappingFunction)

Nici măcar nu m-am obosit să încerc să calculez câte linii de cod te va salva această metodă.
  1. Dacă keynu există în dvs. Mapsau dacă valuepentru această cheie este null, atunci metoda adaugă key-valueperechea transmisă la Map.
  2. Dacă keyexistă și este value != null, atunci metoda își schimbă valoarea în rezultatul executării remappingFunction.
  3. Dacă remappingFunctionreturnează null, atunci keyeste eliminat din colecție.
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));
Ieșire:
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
*scuze, Bruce*

9. Map.putIfAbsent (tasta K, valoarea V)

Anterior, pentru a adăuga o pereche la un Map, dacă nu era deja acolo, trebuia să faceți următoarele:
Map <String, String> map = new HashMap<>();
if (map.get("Lord of the Rings") == null)
    map.put("Lord of the Rings", "John Tolkien");
Acum totul a devenit mult mai ușor:
Map<String, String> map = new HashMap<>();
map.putIfAbsent("Lord of the Rings", "John Tolkien");

10. Map.replace și Map.replaceAll()

Ultimul, dar nu cel din urmă.
  1. Map.replace(K key, V newValue)înlocuiește keyvaloarea lui cu newValue, dacă o astfel de cheie există. Dacă nu, nu se întâmplă nimic.
  2. Map.replace(K key, V oldValue, V newValue)face același lucru, dar numai dacă valoarea curentă pentru keyeste egală cu oldValue.
  3. Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)înlocuiește fiecare valuecu rezultatul funcției.
De exemplu:
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
Nu a mers! Valoarea actuală pentru cheia „Frații Karamazov” este „Fyodor Dostoievski”, nu „Bruce Eckel”, așa că nimic nu s-a schimbat.
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
Am schimbat cu ușurință valorile pentru întreg, Mapfără constructii complicate! PS Să te obișnuiești cu noul este întotdeauna dificil, dar aceste schimbări sunt foarte bune. În orice caz, unele părți ale codului meu sunt cu siguranță mai puțin ca spaghetele decât înainte :) Succes în învățare!
Comentarii
  • Popular
  • Nou
  • Vechi
Trebuie să fii conectat pentru a lăsa un comentariu
Această pagină nu are încă niciun comentariu