Wie Sie wissen, sind unsere Gewohnheiten eine Selbstverständlichkeit. Und wenn Sie sich erst einmal an das Schreiben gewöhnt haben
for (int i = 0; i <......)
, möchte kein Teil von Ihnen dieses Konstrukt erneut erlernen müssen (zumal es recht einfach und verständlich ist). Allerdings werden Schleifen häufig wiederholt verwendet, um dieselben Grundoperationen auszuführen, und Wiederholungen möchten wir am liebsten loswerden. Mit Java 8 hat sich Oracle entschieden, uns dabei zu helfen. Nachfolgend finden Sie die 10 besten Erfassungsmethoden, mit denen Sie eine Menge Zeit und Code sparen.
1. Iterable.forEach(Consumer <? Super T> Aktion)
Der Name spricht für sich. Es durchläuft die als Argument übergebene Sammlung und führt den Aktions-Lambda-Ausdruck für jedes seiner Elemente aus.
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)
Auch hier gibt es nichts Schwieriges. Die Methode durchläuft die Sammlung und entfernt alle Elemente, die übereinstimmenfilter
.
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 + " "));
In einer einzigen Zeile entfernen wir alle Zahlen größer als 5 aus der Liste.
3. Map.forEach(BiConsumer <? super K, ? super V> Aktion)
DieforEach
Methode funktioniert nicht nur für Klassen, die die Collection
Schnittstelle implementieren, sondern auch für 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-Taste, BiFunction<? Super K,? Super V,? Extends V> remappingFunction)
Sieht etwas einschüchternder aus, ist aber eigentlich einfach, wie alle vorherigen. Diese Methode setztkey
den Wert gleich dem Ergebnis der Ausführung mappingFunction
. Zum Beispiel:
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
Der Autor von „Thinking in Java“ ist auf jeden Fall cool! :) :)
5. Map.computeIfAbsent(K-Taste, Funktion <? Super K, ? erweitert V> MappingFunction)
Diese Methode fügt ein neues Element zum hinzuMap
, jedoch nur, wenn noch kein Element mit diesem Schlüssel vorhanden ist. Der zugewiesene Wert ist das Ergebnis der Ausführung von mappingFunction
. Wenn bereits ein Element mit dem Schlüssel vorhanden ist, wird es nicht überschrieben. Es bleibt einfach so wie es ist. Kehren wir zu unseren Büchern zurück und probieren eine neue Methode aus:
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 ist unser mappingFunction
:
public static String getHarryPotterAuthor() {
return "Joanne Rowling";
}
Und hier ist das neue Buch:
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, ? erweitert V> remappingFunction)
Hier haben wir das gleiche Prinzip wieMap.compute()
, aber die Berechnungen werden nur durchgeführt, wenn ein Artikel key
bereits vorhanden ist.
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));
Der erste Aufruf der Funktion brachte keine Änderungen, da es in unserem kein Buch mit dem Titel „Eugen Onegin“ gibt Map
. Doch im zweiten Aufruf änderte das Programm den Autor des Buches „Die Brüder Karamasow“ zu Alexander Puschkin. Ausgang:
_________________
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(Objektschlüssel, V defaultValue)
Diese Methode gibt den entsprechenden Wert zurückkey
. Wenn der Schlüssel nicht vorhanden ist, wird der Standardwert zurückgegeben.
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);
Das ist sehr praktisch:
Unknown author
8. Map.merge(K-Taste, V-Wert, BiFunction<? super V, ? super V, ? erweitert V> remappingFunction)
Ich habe mir nicht einmal die Mühe gemacht, zu berechnen, wie viele Codezeilen Sie mit dieser Methode einsparen.- Wenn dieser
key
in Ihrem nicht vorhanden istMap
oder dervalue
Schlüssel für diesen Schlüssel lautetnull
, fügt die Methode das übergebenekey-value
Paar zum Schlüssel hinzuMap
. - Wenn
key
vorhanden und vorhandenvalue != null
, ändert die Methode ihren Wert in das Ergebnis der AusführungremappingFunction
. - Wenn
remappingFunction
zurückgegeben wirdnull
,key
wird es aus der Sammlung entfernt.
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));
Ausgang:
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
*Entschuldigung, Bruce*
9. Map.putIfAbsent(K-Taste, V-Wert)
Um ein Paar zu einem hinzuzufügenMap
, wenn es noch nicht vorhanden war, mussten Sie bisher Folgendes tun:
Map <String, String> map = new HashMap<>();
if (map.get("Lord of the Rings") == null)
map.put("Lord of the Rings", "John Tolkien");
Jetzt ist alles viel einfacher geworden:
Map<String, String> map = new HashMap<>();
map.putIfAbsent("Lord of the Rings", "John Tolkien");
10. Map.replace und Map.replaceAll()
Zu guter Letzt.Map.replace(K key, V newValue)
ersetztkey
den Wert von durchnewValue
, falls ein solcher Schlüssel vorhanden ist. Wenn nicht, passiert nichts.Map.replace(K key, V oldValue, V newValue)
macht das Gleiche, aber nur, wenn der aktuelle Wert fürkey
gleich istoldValue
.Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)
ersetzt jedesvalue
durch das Ergebnis der Funktion.
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
Es hat nicht funktioniert! Der aktuelle Wert für den Schlüssel „Die Brüder Karamasow“ ist „Fjodor Dostojewski“, nicht „Bruce Eckel“, daher hat sich nichts geändert.
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
Wir haben die Werte für das Ganze ganz einfach und Map
ohne komplizierte Konstrukte geändert! PS: Es ist immer schwierig, sich an das Neue zu gewöhnen, aber diese Änderungen sind wirklich gut. Auf jeden Fall ähneln einige Teile meines Codes definitiv weniger Spaghetti als zuvor :) Viel Glück beim Lernen!
GO TO FULL VERSION