Zoals u weet, zijn onze gewoonten een tweede natuur. En als je eenmaal gewend bent aan schrijven
for (int i = 0; i <......)
, wil geen enkel deel van je deze constructie opnieuw leren (vooral omdat het vrij eenvoudig en begrijpelijk is). Loops worden echter vaak herhaaldelijk gebruikt om dezelfde basisbewerkingen uit te voeren, en herhaling is iets waar we heel graag vanaf willen. Met Java 8 heeft Oracle besloten ons hierbij te helpen. Hieronder staan de 10 beste verzamelmethoden die u een hoop tijd en code besparen.
1. Iterable.forEach (actie Consument <? Super T>)
De naam spreekt voor zich. Het herhaalt de verzameling die als argument is doorgegeven en voert de actie lambda-expressie uit voor elk van zijn elementen.
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 (Predikaat<? super E> filter)
Nogmaals, niets moeilijks hier. De methode herhaalt de verzameling en verwijdert alle elementen die overeenkomenfilter
.
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 + " "));
Op één regel verwijderen we alle getallen groter dan 5 uit de lijst.
3. Map.forEach(BiConsumer <? super K, ? super V> actie)
DeforEach
methode werkt niet alleen voor klassen die de Collection
interface implementeren, maar ook voor 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-toets, BiFunction<? Super K,? Super V,? Breidt V> remappingFunction uit)
Ziet er een beetje intimiderend uit, maar in feite eenvoudig, zoals alle voorgaande. Deze methode steltkey
de waarde gelijk aan het resultaat van de uitvoering mappingFunction
. Bijvoorbeeld:
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
De auteur van "Thinking in Java" is absoluut cool! :)
5. Map.computeIfAbsent (K-toets, functie <? super K,? verlengt V> mappingFunction)
Deze methode voegt een nieuw element toe aan deMap
, maar alleen als er nog geen element met die sleutel is. De toegewezen waarde is het resultaat van het uitvoeren van de mappingFunction
. Als er al een element met de sleutel bestaat, wordt het niet overschreven. Het blijft gewoon zoals het is. Laten we terugkeren naar onze boeken en een nieuwe methode proberen:
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));
Hier is onze mappingFunction
:
public static String getHarryPotterAuthor() {
return "Joanne Rowling";
}
En hier is het nieuwe boek:
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-toets, BiFunction<? super K, ? super V, ? breidt V uit> remappingFunction)
Hier hebben we hetzelfde principe alsMap.compute()
, maar de berekeningen worden alleen uitgevoerd als er key
al een item met bestaat.
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));
De eerste aanroep van de functie heeft geen wijzigingen aangebracht, omdat er geen boek met de titel "Eugene Onegin" in ons Map
. Maar bij de tweede oproep veranderde het programma de auteur van het boek "The Brothers Karamazov" in Alexander Pushkin. Uitgang:
_________________
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 (Objectsleutel, V defaultValue)
Deze methode retourneert de waarde die overeenkomt metkey
. Als de sleutel niet bestaat, wordt de standaardwaarde geretourneerd.
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);
Dit is erg handig:
Unknown author
8. Map.merge (K-toets, V-waarde, BiFunction<? super V, ? super V, ? breidt V> remappingFunction uit)
Ik heb niet eens de moeite genomen om te berekenen hoeveel regels code deze methode u zal besparen.- Als
key
niet bestaat in uwMap
, of als devalue
voor deze sleutel isnull
, dan voegt de methode het doorgegevenkey-value
paar toe aan deMap
. - Als
key
het bestaat en het isvalue != null
, dan verandert de methode zijn waarde in het resultaat van de uitvoeringremappingFunction
. - Indien
remappingFunction
geretourneerdnull
, dankey
wordt het uit de collectie verwijderd.
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));
Uitgang:
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
*sorry Bruce*
9. Map.putIfAbsent (K-toets, V-waarde)
Map
Voorheen moest je het volgende doen om een paar toe te voegen aan een , als het er nog niet was:
Map <String, String> map = new HashMap<>();
if (map.get("Lord of the Rings") == null)
map.put("Lord of the Rings", "John Tolkien");
Nu is alles veel eenvoudiger geworden:
Map<String, String> map = new HashMap<>();
map.putIfAbsent("Lord of the Rings", "John Tolkien");
10. Map.replace en Map.replaceAll()
Tenslotte.Map.replace(K key, V newValue)
vervangtkey
de waarde doornewValue
, als zo'n sleutel bestaat. Zo niet, dan gebeurt er niets.Map.replace(K key, V oldValue, V newValue)
doet hetzelfde, maar alleen als de huidige waarde voorkey
gelijk is aanoldValue
.Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)
vervangt elkvalue
door het resultaat van de functie.
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
Het werkte niet! De huidige waarde voor de sleutel "The Brothers Karamazov" is "Fyodor Dostoevsky", niet "Bruce Eckel", dus er is niets veranderd.
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
We hebben de waarden voor het geheel eenvoudig gewijzigd Map
zonder ingewikkelde constructies! PS Wennen aan het nieuwe is altijd moeilijk, maar deze veranderingen zijn echt goed. In ieder geval lijken sommige delen van mijn code zeker minder op spaghetti dan voorheen :) Veel succes met leren!
GO TO FULL VERSION