CodeGym /Java Blogu /Rastgele /Döngü yazmayı bırak! Java 8'de koleksiyonlarla çalışmak i...
John Squirrels
Seviye
San Francisco

Döngü yazmayı bırak! Java 8'de koleksiyonlarla çalışmak için en iyi 10 uygulama

grupta yayınlandı
Döngü yazmayı bırak!  Java 8 - 1'de koleksiyonlarla çalışmak için en iyi 10 uygulama Bildiğiniz gibi, alışkanlıklarımız doğaldır. Ve bir kez yazmaya alıştığınızda for (int i = 0; i <......), hiçbir parçanız bu yapıyı yeniden öğrenmek zorunda kalmak istemez (özellikle oldukça basit ve anlaşılır olduğu için). Bununla birlikte, döngüler genellikle aynı temel işlemleri gerçekleştirmek için tekrar tekrar kullanılır ve tekrar, kurtulmayı çok istediğimiz bir şeydir. Java 8 ile Oracle, bunu yapmamıza yardım etmeye karar verdi. Aşağıda size tonlarca zaman ve kod kazandıracak en iyi 10 toplama yöntemini bulabilirsiniz.

1. Iterable.forEach(Tüketici <? Süper T> eylemi)

Adı kendisi için konuşur. Argüman olarak iletilen koleksiyonu yineler ve her bir öğesi için eylem lambda ifadesini yürütür.

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(Yüklem<? süper E> filtresi)

Yine, burada zor bir şey yok. Yöntem, koleksiyon üzerinde yinelenir ve eşleşen tüm öğeleri kaldırır 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 + " "));
Tek satırda 5'ten büyük tüm sayıları listeden çıkarıyoruz.

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

Yöntem forEachyalnızca arabirimi uygulayan sınıflar için değil Collection, aynı zamanda 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 tuşu, BiFunction<? Super K,? Super V,? Extends V> remappingFunction)

Biraz daha korkutucu görünüyor, ama aslında öncekiler gibi basit. Bu yöntem, keyyürütmenin sonucuna eşit değerini ayarlar mappingFunction. Örneğin:

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
"Java'da Düşünmek" kitabının yazarı kesinlikle harika! :)

5. Map.computeIfAbsent(K tuşu, İşlev <? süper K, ? V'yi genişletir> mappingFunction)

MapBu yöntem , , ancak o anahtara sahip bir öğeye sahip değilse yeni bir öğe ekler . Atanan değer mappingFunction, . Anahtarı olan bir öğe zaten varsa, üzerine yazılmaz. Sadece olduğu gibi kalacak. Kitaplarımıza dönelim ve yeni bir yöntem deneyelim:

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));
İşte bizim mappingFunction:

public static String getHarryPotterAuthor() {
        return "Joanne Rowling";
    }
Ve işte yeni kitap:

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 tuşu, BiFunction<? süper K, ? süper V, ? V'yi genişletir> remappingFunction)

Burada aynı ilkeye sahibiz Map.compute(), ancak hesaplamalar yalnızca keyzaten bir öğe varsa gerçekleştirilir.

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));
İşleve ilk çağrı herhangi bir değişiklik yapmadı, çünkü "Eugene Onegin" adlı bir kitap yok Map. Ancak ikinci aramada program, "Karamazov Kardeşler" kitabının yazarını Aleksandr Puşkin olarak değiştirdi. Çıktı:

_________________
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(Nesne anahtarı, V defaultValue)

Bu yöntem, karşılık gelen değeri döndürür key. Anahtar yoksa, varsayılan değeri döndürür.

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);
Bu çok uygun:

Unknown author

8. Map.merge(K tuşu, V değeri, BiFunction<? süper V, ? süper V, ? V'yi genişletir> remappingFunction)

Bu yöntemin sizi kaç satır koddan kurtaracağını hesaplama zahmetine bile girmedim.
  1. keyAnahtarınızda yoksa veya Mapfor valuethis key ise null, yöntem geçirilen key-valueçifti Map.
  2. Varsa keyve onun value != nullise, yöntem, yürütmenin sonucu olarak değerini değiştirir remappingFunction.
  3. döndürürse remappingFunction, koleksiyondan kaldırılır null.key

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));
Çıktı:

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
*özür dilerim Bruce*

9. Map.putIfAbsent(K tuşu, V değeri)

Önceden, a'ya bir çift eklemek için Map, zaten orada değilse, aşağıdakileri yapmanız gerekiyordu:

Map <String, String> map = new HashMap<>();
if (map.get("Lord of the Rings") == null)
    map.put("Lord of the Rings", "John Tolkien");
Şimdi her şey çok daha kolay hale geldi:

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

10. Map.replace ve Map.replaceAll()

En son ama en kötü değil.
  1. Map.replace(K key, V newValue)böyle bir anahtar varsa keydeğerini ile değiştirir . newValueDeğilse, hiçbir şey olmaz.
  2. Map.replace(K key, V oldValue, V newValue)aynı şeyi yapar, ancak yalnızca for'un geçerli değeri keyşuna eşitse oldValue.
  3. Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)valueher birini işlevin sonucuyla değiştirir .
Örneğin:

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
İşe yaramadı! "Karamazov Kardeşler" anahtarının şu anki değeri "Bruce Eckel" değil, "Fyodor Dostoyevski"dir, dolayısıyla hiçbir şey değişmemiştir.

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
Herhangi bir karmaşık yapı olmadan , tamamı için değerleri kolayca değiştirdik Map! Not: Yeniye alışmak her zaman zordur ama bu değişiklikler gerçekten çok iyi. Her halükarda, kodumun bazı bölümleri kesinlikle spagetti'ye eskisinden daha az benziyor :) Öğrenmede bol şans!
Yorumlar
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION