자바 8 스 트림 완전 사용 안내

12537 단어 자바stream
스 트림 이 뭐야?Stream자바 1.8 버 전이 제공 하기 시작 한 인터페이스 입 니 다.주로 데이터 집합 에 스 트림 을 사용 하 는 방식 으로 작 동 합 니 다.스 트림 의 요 소 는 가 변 적 이지 않 고 한 번 만 소비 되 며 모든 방법 은 체인 호출 을 지원 합 니 다.Stream API 를 사용 하면 생산성 이 매우 높 고 효율 적 이 며 깨끗 하 며 간결 한 코드 를 쓸 수 있다.
스 트림 인 스 턴 스 를 어떻게 얻 습 니까?Stream정적 구축 방법 을 제공 합 니 다.서로 다른 매개 변 수 를 바탕 으로 Stream 인 스 턴 스 를 만 들 수 있 습 니 다Collection의 하위 인 스 턴 스 호출stream()또는parallelStream()방법 도 Stream 인 스 턴 스 를 얻 을 수 있 습 니 다.두 가지 방법의 차 이 는 후속 실행Stream다른 방법 일 때 단일 스 레 드 인지 다 중 스 레 드 인지 에 있 습 니 다.
Stream stringStream = Stream.of("1", "2", "3");
//       
Stream evenNumStream = Stream.iterate(0, n -> n + 2);

List strList = new ArrayList<>();
strList.add("1");
strList.add("2");
strList.add("3");
Stream strStream = strList.stream();
Stream strParallelStream = strList.parallelStream();

filter filter방법 은 지 정 된 조건 에 따라 여과 하여 조건 에 맞 는 흐름 을 되 돌려 줍 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//         ,positiveNumStream -> (1,2,3)
Stream positiveNumStream = numStream.filter(num -> num > 0);

map map방법 은 흐름 속 의 모든 요 소 를 지정 한 변환 논 리 를 실행 하고 다른 유형의 요소 의 흐름 을 되 돌려 주 는 데 사 용 됩 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//       
Stream strStream = numStream.map(String::valueOf);

mapToInt mapToLong mapToDouble
이 세 가지 방법 은map방법 에 대한 패키지 입 니 다.공식 적 으로 각 유형 에 대해 단독으로 정 의 된 Stream 으로 돌아 갑 니 다.이 Stream 은 각 유형 에 맞 는 다른 조작 방법 도 제공 합 니 다.
Stream stringStream = Stream.of("-2", "-1", "0", "1", "2", "3");
IntStream intStream = stringStream.mapToInt(Integer::parseInt);
LongStream longStream = stringStream.mapToLong(Long::parseLong);
DoubleStream doubleStream = stringStream.mapToDouble(Double::parseDouble);

flatMap flatMap방법 은 스 트림 에 있 는 모든 요 소 를 다른 유형의 요소 로 전환 하 는 데 사 용 됩 니 다.예 를 들 어 현재 하나의 주문(Order)목록 이 있 고 모든 주문 서 는 여러 개의 상품(itemList)을 포함 합 니 다.모든 주문 서 를 얻 으 려 면 이 방법 을 사용 할 수 있 습 니 다.다음 과 같 습 니 다.
Stream allItemStream = orderList.stream().flatMap(order -> order.itemList.stream());

flatMapToInt flatMapToLong flatMapToDouble
이 세 가지 방법 은flatMap방법 에 대한 패키지 입 니 다.공식 적 으로 각 유형 에 대해 단독으로 정 의 된 Stream 으로 돌아 갑 니 다.사용 방법 은 같 습 니 다.
distinct distinct방법 은 흐 르 는 원소 의 무 게 를 제거 하 는 데 사용 되 며,원소 의 중복 사용 여 부 를 판단 하 는 것 은equals방법
Stream numStream = Stream.of(-2, -1, 0, 0, 1, 2, 2, 3);
//       ,uniqueNumStream -> (-2, -1, 0, 1, 2, 3)
Stream uniqueNumStream = numStream.distinct();

sorted sorted인삼 이 없 는 방법 과 인삼 이 있 는 방법 이 있 습 니 다.대류 중의 요 소 를 정렬 하 는 데 사 용 됩 니 다.무 참 방법 요구 흐름 중의 요 소 는 반드시 실현Comparable인터페이스,그렇지 않 으 면java.lang.ClassCastException이상
Stream unorderedStream = Stream.of(5, 6, 32, 7, 27, 4);
//           ,orderedStream -> (4, 5, 6, 7, 27, 32)
Stream orderedStream = unorderedStream.sorted();

참조 방법sorted(Comparator super T> comparator)요소 가 필요 없 음Comparable인터페이스,지정 한 요소 비교 기 를 통 해 대류 내 요 소 를 정렬 합 니 다.
Stream unorderedStream = Stream.of("1234", "123", "12", "12345", "123456", "1");
//                ,orderedStream -> ("1", "12", "123", "1234", "12345", "123456")
Stream orderedStream = unorderedStream.sorted(Comparator.comparingInt(String::length));

peek peek방법 은 요소 의 순서 와 수량 을 조정 하지 않 고 모든 요 소 를 소비 한 다음 에 새로운 흐름 이 생 길 수 있 습 니 다.문서 의 설명 에 따 르 면 주로 대류 가 실 행 된 중간 과정 에서 debug 를 할 때 사용 합 니 다.Stream사용 할 때 체인 식 으로 사용 되 기 때문에 여러 번 스 트림 작업 을 수행 할 수 있 습 니 다.모든 요소 가 여러 번 흐 르 는 작업 중간 에 흐 르 는 상황 을 보고 싶다 면 이 방법 을 사용 하여 실현 할 수 있다.
Stream.of("one", "two", "three", "four")
     .filter(e -> e.length() > 3)
     .peek(e -> System.out.println("Filtered value: " + e))
     .map(String::toUpperCase)
     .peek(e -> System.out.println("Mapped value: " + e))
     .collect(Collectors.toList());
     
  :
Filtered value: three
Mapped value: THREE
Filtered value: four
Mapped value: FOUR

limit(long maxSize) limit방법 은 대류 에 대해 순서 적 으로 캡 처 합 니 다.첫 번 째 요소 부터 최대maxSize개 요 소 를 보존 합 니 다.
Stream stringStream = Stream.of("-2", "-1", "0", "1", "2", "3");
//   3   ,subStringStream -> ("-2", "-1", "0")
Stream subStringStream = stringStream.limit(3);

skip(long n) skip방법 은 앞의 n 개 요 소 를 건 너 뛰 는 데 사 용 됩 니 다.흐 르 는 요소 의 수량 이 n 이 부족 하면 빈 흐름 으로 돌아 갑 니 다.
Stream stringStream = Stream.of("-2", "-1", "0", "1", "2", "3");
//   3   ,subStringStream -> ("1", "2", "3")
Stream subStringStream = stringStream.skip(3);

forEach forEach방법의 역할 은 일반적인 for 순환 과 유사 하지만,이것 은 다 중 스 레 드 를 지원 할 수 있 지만,옮 겨 다 니 는 순 서 는 보장 되 지 않 습 니 다.
Stream stringStream = Stream.of("-2", "-1", "0", "1", "2", "3");
//         
stringStream.forEach(System.out::println);
//         
stringStream.parallel().forEach(System.out::println);

forEachOrdered forEachOrdered방법 은 순 서 를 옮 겨 다 닐 수 있 습 니 다.예 를 들 어 이 흐름 은 외부 에서 들 어 온 것 입 니 다.그리고 그 전에 호출 된parallel방법 은 다 중 스 레 드 실행 을 시작 하면 이 방법 을 사용 하여 단일 스 레 드 순 서 를 옮 겨 다 닐 수 있 습 니 다.
Stream stringStream = Stream.of("-2", "-1", "0", "1", "2", "3");
//        
stringStream.forEachOrdered(System.out::println);
//         ,                
//stringStream.parallel().forEachOrdered(System.out::println);

toArray toArray무 참 과 유 참 방법 이 있 습 니 다.무 참 방법 은 흐 르 는 요 소 를 Object 배열 로 변환 하 는 데 사 용 됩 니 다.
Stream stringStream = Stream.of("-2", "-1", "0", "1", "2", "3");
Object[] objArray = stringStream.toArray();

유 참 방법toArray(IntFunctiongenerator)스 트림 의 요 소 를 지정 한 형식의 요소 배열 로 변환 하 는 것 을 지원 합 니 다.
Stream stringStream = Stream.of("-2", "-1", "0", "1", "2", "3");
String[] strArray = stringStream.toArray(String[]::new);

reduce reduce세 가지 과부하 방법 이 있 는데,역할 은 대류 내 요소 에 대해 누진 작업 을 하 는 것 이다.
첫번째reduce(BinaryOperator accumulator)accumulator누진 작업 을 위 한 구체 적 인 계산
단일 스 레 드 등 아래 코드
boolean foundAny = false;
T result = null;
for (T element : this stream) {
  if (!foundAny) {
      foundAny = true;
      result = element;
  }
  else
      result = accumulator.apply(result, element);
}
return foundAny ? Optional.of(result) : Optional.empty();
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//     
Optional min = numStream.reduce(BinaryOperator.minBy(Integer::compareTo));
//   -2
System.out.println(min.get());

//     5    
numStream = Stream.of(-2, -1, 0, 1, 2, 3).filter(num -> num > 5);
//     
min = numStream.reduce(BinaryOperator.minBy(Integer::compareTo));
//   Optional.empty
System.out.println(min);

두 번 째reduce(T identity, BinaryOperator accumulator)identity누진 작업 의 초기 값accumulator동상
단일 스 레 드 등가 다음 코드
T result = identity;
for (T element : this stream)
  result = accumulator.apply(result, element)
return result;
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//          ,sum=3
int sum = numStream.reduce(0, Integer::sum);

세 번 째reduce(U identity, BiFunction accumulator, BinaryOperator combiner)identity|accumulator동상combiner다 중 스 레 드 실행 에 사용 되 는 경우 최종 결 과 를 통합 합 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
int sum = numStream.parallel().reduce(0, (a, b) -> {
    System.out.println("accumulator  :" + a + " + " + b);
    return a + b;
}, (a, b) -> {
    System.out.println("combiner  :" + a + " + " + b);
    return a + b;
});
System.out.println("    :"+sum);

  :
accumulator  :0 + -1
accumulator  :0 + 1
accumulator  :0 + 0
accumulator  :0 + 2
accumulator  :0 + -2
accumulator  :0 + 3
combiner  :2 + 3
combiner  :-1 + 0
combiner  :1 + 5
combiner  :-2 + -1
combiner  :-3 + 6
    :3

collect collect두 가지 과부하 방법 이 있 습 니 다.주요 역할 은 흐름 속 의 요 소 를 집합 으로 다른Collection의 하위 클래스 로 전환 하 는 것 입 니 다.그 내 부 는 앞의 누진 작업 과 유사 합 니 다.
첫번째collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)supplier실행 을 시작 할 때의 기본 결 과 를 되 돌려 야 합 니 다accumulator누진 계산 용combiner다 중 스 레 드 합병 결과 에 사용 합 니 다.
단일 스 레 드 실행 은 다음 코드 와 같 습 니 다.
R result = supplier.get();
for (T element : this stream)
  accumulator.accept(result, element);
return result;

두 번 째collect(Collector super T, A, R> collector)collector사실은 위의 방법 매개 변수 에 대한 패키지 입 니 다.내부 실행 논 리 는 같 습 니 다.다만 JDK 는 기본 적 인Collector실현 을 제공 합 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
List numList = numStream.collect(Collectors.toList());
Set numSet = numStream.collect(Collectors.toSet());

min min방법 은 흐름 내 요소 의 최소 치 를 계산 하 는 데 사용 된다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
Optional min = numStream.min(Integer::compareTo);

max min방법 은 흐름 내 요소 의 최대 치 를 계산 하 는 데 사용 된다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
Optional max = numStream.max(Integer::compareTo);

count count방법 은 흐름 내 요소 의 총 개 수 를 통계 하 는 데 사용 된다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//count=6
long count = numStream.count();

anyMatch anyMatch방법 은 스 트림 내 요소 가 지정 한 조건 에 부합 되 는 요소 가 있 는 지 검증 하 는 데 사 용 됩 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//        ,hasPositiveNum=true
boolean hasPositiveNum = numStream.anyMatch(num -> num > 0);

allMatch allMatch방법 은 스 트림 내 요소 가 지정 한 조건 에 부합 되 는 지 검증 하 는 데 사 용 됩 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//         ,allNumPositive=false
boolean allNumPositive = numStream.allMatch(num -> num > 0);

noneMatch noneMatch방법 은 스 트림 내 요소 가 지정 한 조건 에 부합 되 지 않 는 지 검증 하 는 데 사 용 됩 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//        0   ,noNegativeNum=false
boolean noNegativeNum = numStream.noneMatch(num -> num < 0);

findFirst findFirst첫 번 째 요 소 를 가 져 오 는 방법 입 니 다.흐름 이 비어 있 으 면 Optional.empty 로 돌아 갑 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
//       ,firstNum=-2
Optional firstNum = numStream.findFirst();

findAny findAny방법 은 스 트림 의 임의의 요 소 를 가 져 오 는 데 사 용 됩 니 다.스 트림 이 비어 있 으 면 Optional.empty 로 돌아 갑 니 다.다 중 스 레 드 를 사용 할 수 있 기 때문에 매번 같은 요 소 를 되 돌려 주 는 것 은 보장 되 지 않 습 니 다.
Stream numStream = Stream.of(-2, -1, 0, 1, 2, 3);
Optional anyNum = numStream.findAny();

좋은 웹페이지 즐겨찾기