1. 확인

데이터 스트림을 함께 연결하는 방법을 배우는 데 이미 지루할 수 있습니다. 마침내 데이터로 무언가를 하려고 합니다.

Stream클래스에는 스트림을 구성하지 않고 스트림에 어떤 종류의 데이터가 있는지 확인하는 세 가지 표준 메서드가 있습니다. 이러한 메서드는 anyMatch(), allMatch()및 입니다 noneMatch().

boolean anyMatch(rule)방법

이 메서드는 스트림에 메서드에 전달된 규칙을 만족하는 요소가 하나 이상 있는지 확인합니다. 그러한 요소가 있으면 메서드는 를 반환하고 true그렇지 않으면 를 반환합니다 false.

암호 메모
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
boolean result = stream.anyMatch(x -> x > 0);

true
Stream<Integer> stream = Stream.of(1, -2, 3, -4, 5);
boolean result = stream.anyMatch(x -> x > 0);

true
Stream<Integer> stream = Stream.of(1, -2, 3, -4, 5);
boolean result = stream.filter(x -> x < 0).anyMatch(x -> x > 0);

false

마지막 예에서는 먼저 0보다 작은 요소만 유지한 다음 결과를 확인하여 필터링된 요소 중 0보다 큰 것이 있는지 확인합니다. 물론 그러한 요소는 더 이상 존재하지 않습니다.

부울 allMatch(rule) 메서드

이 메서드는 스트림의 모든 요소가 규칙(조건자라고도 함)과 일치하는지 확인합니다. 규칙은 메서드에 대한 인수로 전달됩니다.

암호 메모
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
boolean result = stream.allMatch(x -> x > 0);
true
(0보다 큰 모든 요소)
Stream<Integer> stream = Stream.of(1, -2, 3, -4, 5);
boolean result = stream.allMatch(x -> x > 0);
false
(0보다 작거나 같은 요소가 있습니까?)
Stream<Integer> stream = Stream.of(1, -2, 3, -4, 5);
boolean result = stream.filter(x -> x < 0).allMatch(x -> x < 0);
true
(우리는 0보다 작은 요소를 유지했습니다)

마지막 예에서는 먼저 0보다 작은 요소만 필터를 통과하도록 허용한 다음 유지된 모든 요소가 0보다 작은지 확인합니다. 확인 결과 긍정적인 결과가 나타납니다.

부울 noneMatch(rule) 메서드

noneMatch()메서드는 스트림에 전달된 규칙과 일치하는 요소가 없는지 확인합니다. 그것은 anyMatch()방법의 반대와 같습니다.

암호 메모
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
boolean result = stream.noneMatch(x -> x > 0);

false
Stream<Integer> stream = Stream.of(1, -2, 3, -4, 5);
boolean result = stream.noneMatch(x -> x > 0);

false
Stream<Integer> stream = Stream.of(1, -2, 3, -4, 5);
boolean result = stream.filter(x -> x < 0).noneMatch(x -> x > 0);

true

4
과제
Java Core,  레벨 6레슨 5
잠금
join: at the right time in the right place
The join method is very useful and is often used to terminate a thread. Think about where and on what object you need to call this method to have the result displayed
18
과제
Java Core,  레벨 6레슨 5
잠금
Horse racing
Programming is better than gambling... Still, horse races and other races perfectly illustrate multithreading! Figure out what the code does, and implement a method that counts the number of horses that have crossed the finish line. One more thing: you need to wait for the longshots to finish the race.

2. 유틸리티 클래스: Optional클래스

때로는 프로그래머가 참조로 작업하는 것이 매우 불편합니다 null. 예를 들어 두 문자열을 비교한다고 가정합니다. 두 변수가 모두 가 아닌 경우 null간단히 호출하면 s1.equals(s2)모든 것이 작동합니다. 하지만 그럴 s1수 있다면 .nullNullPointerException

이것이 프로그래머들이 유틸리티 클래스를 생각해 낸 이유입니다 Optional<T>. 코드는 대략 다음과 같습니다.

암호 메모
class Optional<Type>
{
   private final Type value;
   private Optional() { this.value = null;}
   private Optional(value) { this.value = value;}
   public static <Type> Optional<Type> of(Type value)
   {
      return new Optional<Type>(value);
   }

   public boolean isPresent()
   {
      return value != null;
   }

   public boolean isEmpty()
   {
      return value == null;
   }

   public Type get()
   {
      if (value == null)
      {
         throw new NoSuchElementException();
      }
      return value;
   }

   public Type orElse(Type other)
   {
      return value != null ? value : other;
   }

   public Type orElseThrow()
   {
      if (value == null)
      {
         throw new NoSuchElementException();
      }
      return value;
   }
}










값이 아닌지 확인합니다. null



값이 있는지 확인합니다. null




저장된 값을 반환합니다. 값이 null인 경우 예외를 throw합니다.







저장된 null이 아닌 값을 반환합니다. 또는 저장된 값이 인 경우 null메서드 인수로 전달된 값을 반환합니다.



null이 아닌 저장된 값을 반환하거나 값이 null인 경우 예외를 throw합니다.

이 클래스의 목적은 단순히 T 개체(유형이 T인 개체에 대한 참조)를 저장하는 것입니다. 객체 내부의 객체 Optional<T>참조는 null.

이 클래스를 사용하면 프로그래머가 약간 더 예쁜 코드를 작성할 수 있습니다. 비교해보자:

옵션 사용 선택 사항을 사용하지 않음
public void printString(String s)
{
   Optional<String> str = Optional.ofNullable(s);
   System.out.println(str.orElse(""));
}
public void printString(String s)
{
   String str = s != null ? s : "";
   System.out.println(str)
}

한 개체는 참조를 저장하더라도 메서드를 사용하여 항상 다른 개체 Optional와 비교할 수 있습니다 .Optionalequalsnull

간단히 말해서 이 클래스를 사용하면 객체가 값을 저장하는 경우 Optional"아름다운" 검사 및 "아름다운" 작업을 작성할 수 있습니다 .nullOptionalnull


9
과제
Java Core,  레벨 6레슨 5
잠금
Promotion during political debates
Mr Chump is our candidate! And we'll help him a bit by making him give a speech, and then another, and then another during a political debate. We'll help him a little by making him talk until all the available time has been taken. Threads come to our rescue!

3. 요소 찾기

수업 으로 돌아가자 Stream. 이 Stream클래스에는 스트림에서 요소를 검색할 수 있는 4개의 추가 메서드가 있습니다. 이러한 메서드는 findFirst(), findAny(), min()및 입니다 max().

Optional<T> findFirst()방법

findFirst()메서드는 단순히 스트림의 첫 번째 요소를 반환합니다. 그게 전부입니다.

여기서 주목해야 할 더 흥미로운 점은 메서드가 개체를 반환하는 것이 아니라 T래퍼 Optional<T>개체를 반환한다는 것입니다. null이렇게 하면 개체 찾기에 실패한 후 메서드가 반환되지 않습니다 .

예:

ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, "Hello", "how's", "life?");
String str = list.stream().findFirst().get(); // Hello

더 명확하게 하기 위해 마지막 줄을 여러 줄로 나누겠습니다.

ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, "Hello", "how's", "life?");

Stream<String> stream = list.stream();
Optional<String> result = stream.findFirst();
String str = result.get(); // Hello

마지막 get()방법은 단순히 개체 내부에 저장된 값을 검색하는 것입니다 Optional.

Optional<T> findAny()방법

findAny()메서드는 스트림에서 모든 요소를 ​​반환하고 거기서 끝납니다. 이 방법은 와 유사 findFirst()하지만 병렬 작업에 사용되는 스트림에 적합합니다.

스트림을 병렬로 처리할 때 스트림의 일부에서 요소가 이미 발견되었을 수 있지만 첫 번째인지 여부는 아직 명확하지 않습니다.

많은 요소가 모든 필터와 일치하고 프로그래머가 그 중 첫 번째 요소를 정확하게 얻는 것이 중요하다면 메서드를 findFirst()호출해야 합니다. 프로그래머가 실제로 0 또는 1개의 요소가 모든 필터와 일치한다는 것을 알고 있다면 단순히 호출하는 것으로 충분하며 이는 findAny()더 빠를 것입니다.

Optional<T> min(Comparator<T>)방법

min()메서드는 comparator개체를 사용하여 스트림의 모든 요소를 ​​비교하고 최소 요소를 반환합니다. 비교 객체를 정의하는 가장 편리한 방법은 람다 함수를 사용하는 것입니다.

가장 짧은 문자열을 검색하는 예:

ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, "Hello", "how's", "life?");
String min = list.stream().min( (s1, s2)-> s1.length()-s2.length() ).get();

Optional<T> max(Comparator<T>)방법

max()메서드는 comparator개체를 사용하여 스트림의 모든 요소를 ​​비교하고 최대 요소를 반환합니다. 비교 객체를 정의하는 가장 편리한 방법은 람다 함수를 사용하는 것입니다.

가장 긴 문자열을 검색하는 예:

ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, "Hello", "how's", "life?");
String max = list.stream().max( (s1, s2)-> s1.length()-s2.length() ).get();
4
과제
Java Core,  레벨 6레슨 5
잠금
Justice
Justice is the name of an ancient Terrian deity that no one ever saw in the flesh. That said, Justice is sometimes encountered in man-made systems. We've got some mice here. For some reason, one of the mice, the alpha male, eats first while the others wait. Figure out why and remove this method call.
9
과제
Java Core,  레벨 6레슨 5
잠금
Arranging calls to join()
First, the cat gives birth to kittens. Then all the kittens climb out of the basket in random order. Finally, the cat brings them back into the basket. These events for one cat may be interspersed with events for another cat. Now implement this scenario with join().