📗 Docs

[Java] Stream - Array에서 min, max 구하기

파일과 미디어
date
Apr 6, 2023
slug
Java-Stream
author
status
Public
tags
Java
Blog
summary
Stream max,min
type
Post
thumbnail
category
📗 Docs
updatedAt
Apr 19, 2023 03:22 PM
int[] array = new int[] {3,4,1,2};
List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
int minIndex = IntStream.range(0,list.size()).boxed()
	            .min(Comparator.comparingInt(list::get))
	            .get();  // or throw if empty list
System.out.println(minIndex);
		
int maxIndex = IntStream.range(0,list.size()).boxed()
	            .max(Comparator.comparingInt(list::get))
	            .get();  // or throw if empty list
System.out.println(maxIndex);

Stream에서 boxed()를 쓰는 경우?

public final Stream<Integer> boxed() {

  return mapToObj(Integer::valueOf, 0);

} //in stream의 boxed()소스
  • Integer.valueOf() → Integer 래퍼(Wrapper)객체를 반환
  • 즉, boxed()메소드는 IntStream 같이 원시 타입에 대한 스트림 지원을 클래스 타입(예: IntStream → Stream<Integer>)으로 전환하여 전용으로 실행 가능한 기능을 수행하기 위해 존재.
[ int자체로는 Collection에 못 담기 때문에 Integer 클래스로 변환하여 List<Integer>로 담기 위해 ]