CodeGym/Java Blog/무작위의/루프 작성을 중지하십시오! Java 8에서 컬렉션 작업을 위한 상위 10가지 모범 사례
John Squirrels
레벨 41
San Francisco

루프 작성을 중지하십시오! Java 8에서 컬렉션 작업을 위한 상위 10가지 모범 사례

무작위의 그룹에 게시되었습니다
회원
루프 작성을 중지하십시오!  Java 8 - 1에서 컬렉션 작업을 위한 상위 10가지 모범 사례 아시다시피 우리의 습관은 제2의 천성입니다. 그리고 일단 글쓰기에 익숙해지면 for (int i = 0; i <......)이 구조를 다시 배워야 할 필요가 없습니다(특히 매우 간단하고 이해하기 쉽기 때문에). 그러나 루프는 종종 동일한 기본 작업을 수행하는 데 반복적으로 사용되며 반복은 제거하고 싶은 부분입니다. Oracle은 Java 8을 통해 우리가 이를 지원하기로 결정했습니다. 다음은 많은 시간과 코드를 절약할 수 있는 10가지 최고의 수집 방법입니다.

1. Iterable.forEach(소비자 <? 슈퍼 T> 액션)

그 이름은 그 자체로 말합니다. 인수로 전달된 컬렉션을 반복하고 각 요소에 대해 작업 람다 식을 실행합니다.
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.
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 + " "));
한 줄로 목록에서 5보다 큰 모든 숫자를 제거합니다.

3. Map.forEach(BiConsumer <?슈퍼K, ?슈퍼V>액션)

forEach방법은 인터페이스를 구현하는 클래스뿐만 Collection아니라 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 키, BiFunction<? Super K,? Super V,? Extends V> remappingFunction)

조금 더 위협적으로 보이지만 실제로는 이전의 모든 것과 마찬가지로 간단합니다. 이 메서드는 key실행 결과와 같은 값을 설정합니다 mappingFunction. 예를 들어:
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
"Thinking in Java"의 저자는 확실히 멋집니다! :)

5. Map.computeIfAbsent(K 키, 기능 <? 슈퍼 K, ? 확장 V> mappingFunction)

이 메서드는 에 새 요소를 추가 Map하지만 해당 키가 있는 요소가 아직 없는 경우에만 해당합니다. 할당된 값은 를 실행한 결과입니다 mappingFunction. 키가 있는 요소가 이미 있으면 덮어쓰지 않습니다. 단순히 그대로 유지됩니다. 책으로 돌아가서 새로운 방법을 시도해 봅시다.
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));
여기 우리의 mappingFunction:
public static String getHarryPotterAuthor() {
        return "Joanne Rowling";
    }
그리고 여기 새 책이 있습니다.
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 키, BiFunction<? 슈퍼 K, ? 슈퍼 V, ? 확장 V> 리매핑 기능)

여기서는 와 원리는 같지만 가 Map.compute()있는 항목이 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.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));
함수에 대한 첫 번째 호출은 변경되지 않았습니다 Map. . 그러나 두 번째 호출에서 프로그램은 "The Brothers Karamazov"라는 책의 저자를 Alexander Pushkin으로 변경했습니다. 산출:
_________________
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(객체 키, V defaultValue)

이 메서드는 에 해당하는 값을 반환합니다 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");

String igor = books.getOrDefault("The Tale of Igor's Campaign", "Unknown author");
System.out.println(igor);
이것은 매우 편리합니다.
Unknown author

8. Map.merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

이 방법으로 몇 줄의 코드를 절약할 수 있는지 계산하려고 애쓰지도 않았습니다.
  1. key에 가 없거나 이 키에 대한 Map가 이면 메서드는 전달된 쌍을 에 추가합니다 .valuenullkey-valueMap
  2. key존재하고 이면 value != null메서드는 해당 값을 실행 결과로 변경합니다 remappingFunction.
  3. remappingFunction반환 하면 컬렉션에서 제거됩니다.nullkey
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));
산출:
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
*미안해, 브루스*

9. Map.putIfAbsent(K 키, V 값)

이전에는 에 쌍을 추가하려면 Map아직 없는 경우 다음을 수행해야 했습니다.
Map <String, String> map = new HashMap<>();
if (map.get("Lord of the Rings") == null)
    map.put("Lord of the Rings", "John Tolkien");
이제 모든 것이 훨씬 쉬워졌습니다.
Map<String, String> map = new HashMap<>();
map.putIfAbsent("Lord of the Rings", "John Tolkien");

10. Map.replace 및 Map.replaceAll()

마지막으로 중요합니다.
  1. Map.replace(K key, V newValue)key해당 키가 존재하는 경우 의 값을 로 바꿉니다 newValue. 그렇지 않으면 아무 일도 일어나지 않습니다.
  2. Map.replace(K key, V oldValue, V newValue)동일한 작업을 수행하지만 의 현재 값이 와 key같은 경우에만 oldValue.
  3. Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)value각각을 함수의 결과로 바꿉니다 .
예를 들어:
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
작동하지 않았습니다! "The Brothers Karamazov" 키의 현재 값은 "Bruce Eckel"이 아닌 "Fyodor Dostoevsky"이므로 변경된 사항이 없습니다.
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
Map복잡한 구성 없이 전체 값을 쉽게 변경했습니다 ! 추신 새로운 것에 익숙해지는 것은 항상 어려운 일이지만 이러한 변화는 정말 좋습니다. 어쨌든 내 코드의 일부 부분은 이전보다 확실히 스파게티 같지 않습니다 :) 학습에 행운을 빕니다!
코멘트
  • 인기
  • 신규
  • 이전
코멘트를 남기려면 로그인 해야 합니다
이 페이지에는 아직 코멘트가 없습니다