https://myhappyman.tistory.com/77
JAVA 8 - Stream 사용하기 - 1(filter, 중복제거)
자바 8에서는 Stream이 추가되었는데, 이 기술은 컬렉션이나 배열등을 람다식으로 표현하여 간결하고 가독성 좋은 코드를 만들어주고 복잡하고 많은 양의 코드를 원하는 인스턴스끼리 조합하여 필터링을 해주는등..
myhappyman.tistory.com
https://myhappyman.tistory.com/78
JAVA 8 - Stream 사용하기 - 2(sorted 데이터 정렬)
Stream 사용하기 1에 이어서 이번엔 Stream의 sorted를 사용해보겠습니다. 배열, 컬렉션에 담긴 데이터를 정렬하는 예제를 보겠습니다. sorted String배열 정렬하기. String[] animals = {"rabbit", "fox", "cat",..
myhappyman.tistory.com
1, 2에서 Stream을 통해 필터링, 중복제거, 정렬등을 봤는데, 사실 사용하면서 최종연산까지는 하지 않고 Stream객체에 담아두고 해당 데이터를 확인할때 최종연산인 forEcah를 사용해서 데이터를 확인했다.
Stream에는 최종연산이 존재하는데 이를 통해 Stream을 완전히 닫아버리고 종료하게 된다.
즉, Stream은 재사용이 불가하다.
Stream의 최종연산자들의 사용법에 대해 알아보겠습니다.
count
public static void main(String[] args) {
//count
List<String> words = Arrays.asList("book", "desk", "keyboard", "mouse", "cup");
int count = (int) words.stream().filter(w->w.contains("o")).count();
System.out.println("count >" + count);
}
"o"가 포함된 Stream의 개수를 찾습니다.
min
public static void main(String[] args) {
List<Integer> cal = Arrays.asList(49, 123, 22, 55, 21);
//min
int min = cal.stream().min(Comparator.comparing(x-> x)).get();
System.out.println("min >" + min);
}
Integer 컬렉션의 최소값을 가져옵니다.
max
public static void main(String[] args) {
List<Integer> cal = Arrays.asList(49, 123, 22, 55, 21);
//max
int max = cal.stream().max(Comparator.comparing(x-> x)).get();
System.out.println("max >" + max);
}
Integer 컬렉션의 최대값을 가져옵니다.
reduce
public static void main(String[] args) {
List<Integer> cal = Arrays.asList(49, 123, 22, 55, 21);
//reduce
Integer reduce = cal.stream().reduce((x, y) -> x+y).get();
System.out.println("reduce >" + reduce);
}
누적된 값을 가져옵니다.
collect
public static void main(String[] args) {
List<Integer> cal = Arrays.asList(49, 123, 22, 55, 21);
//collect
List<Integer> newList = cal.stream().filter(x-> x > 80).collect(Collectors.toList());
newList.forEach(System.out::println);
}
스트림 객체를 원하는 컬렉션형태로 파싱해줍니다.
forEach
public static void main(String[] args) {
List<Integer> cal = Arrays.asList(49, 123, 22, 55, 21);
//forEach
cal.stream().forEach(x-> System.out.print(x + " "));
}
반복문입니다. 컬렉션의 데이터를 각각 호출해줍니다.
'JAVA' 카테고리의 다른 글
자바스크립트에서 문자열 버퍼로 넘기고 자바에서 버퍼를 문자열로 받기 (0) | 2020.03.10 |
---|---|
JAVA8 - 함수적 인터페이스 Function (0) | 2020.02.18 |
JAVA8 - Stream 사용하기 - 2(sorted 데이터 정렬) (0) | 2020.02.12 |
JAVA8 - Stream 사용하기 - 1(filter, 중복제거) (0) | 2020.02.12 |
JAVA - 오토박싱, 언박싱 (Autoboxing and Unboxing) (0) | 2020.02.07 |