jgwk
stream (1) 본문
sql 처럼 자바에서 데이터를 처리할 수 있을까? 그에 대한 자바의 대답이 stream api 이다.
처음에 단어만 듣고서 개선된 input/output stream 이 새로 나왔나 싶었는데, 데이터 처리의 흐름을 표현하기 위한 단어였다. 연결된 메서드와 람다를 사용한 데이터의 처리방법 이다.
대부분의 자료형들은 직접 스트림을 열거나, 유틸리티를 통해 열 수 있게 되어있다. 스트림을 여는 방법이 다양해 보인다. 쓰면서 익숙해져야 겠다.
예제를 첨부한다.
public class Basic {
public static void main(String[] args) {
collection();
array();
varargs();
range();
random();
lambda();
empty();
}
private static void collection() {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
list.stream()
.forEach(System.out::println);
}
private static void array() {
String[] array = new String[] {"11", "12", "13", "14"};
Arrays.stream(array)
.forEach(System.out::println);
Arrays.stream(array, 0, 1)
.forEach(System.out::println);
}
private static void varargs() {
Stream.of(21, 22, 23, 24)
.forEach(System.out::println);
}
private static void range() {
IntStream.range(31, 35)
.forEach(System.out::println);
}
private static void random() {
new Random().ints(4)
.forEach(System.out::println);
}
private static void lambda() {
Stream.iterate(41, n -> n+1)
.limit(4)
.forEach(System.out::println);
AtomicInteger i = new AtomicInteger(51);
Stream.generate(() -> i.getAndIncrement())
.limit(4)
.forEach(System.out::println);
}
private static void empty() {
Stream<String> s = Stream.empty();
System.out.println(s.count());
}
}
참조
'java' 카테고리의 다른 글
intellij 처음 설정 (0) | 2022.11.14 |
---|---|
spring profile or maven profile (0) | 2021.11.28 |
lambda (2) - method references (0) | 2021.05.24 |
lambda (1) (0) | 2021.05.24 |
openjdk 설치 (mac, brew, adopt) (0) | 2021.04.13 |
Comments