카테고리 없음

java8 람다, 스트림

아디봉 2022. 10. 18. 07:10

 

람다

매개변수 2개인 람다

(String first, String second) -> {
int difference = first.length() - second.length();
if (difference < 0 ) {
return -1; 
} else if (difference > 0) {
return 1;
} else {
return 0
}
}


매개변수가 없는 메서드 

Runnable task = () {
for(int i=0; i< 100; i ++) doWork();
}

 

스트림 
String content = new String(Files.readAllBytes(
paths.get("")), StandardCharsets.UTF-8); // 파일을 문자열로 읽어옴
List<String> words = List.of(contents.split("\\PL+"));
//단어를 분리한다.(비문자 글자가 아닌문자)를 구분자로 사용해서


숫자 계산 

이전 방법 

int count = 0;
for(String w : words) {
if(w.length() > 12) count++;
}


List 컬렉션을 스트림 이용

long count = words.stream()
.filter(w -> w.length() > 12)
.count();


병렬로 이용하고 싶다면 

long count = words.parallelStream()
.filter(w -> w.length() > 12)
.count();


- Collection 인터페이스 stream메서드를 사용
- 배열일 때 정적 메서드 Stream.of를 사용

배열을 스트림 이용
Stream <String> song = Stream.of("gently", "down", "the", "stream");

배열의 일부를 stream을 만들 때
Arrays.stream(array, from, to)

배열 요소가 없는 stream을 만들 때 
Stream <String> silence = Stream.empty();


인수 없는 함수를 받는다. generate

0,1,2,3, 같은 수열을 만들 때iterate 

filter, map, flatMap 메서드 
filter 변환은 특정 조건과 일치하는 요소로 구성된 새 스트림을 돌려준다.

List <String> words =...;
Stream <String> longWords = words.stream(). filter(w -> w.length() > 12);


map을 사용하면 지정한 함수를 각 요소에 적용한 결과들을 담은 새 스트림을 만든다.

스트림에 값을 특정 방식으로 변환하고 싶을 때  해당 변환을 수행하는 함수를 map메서드에 전달 

Stream<String> firstLetters = words.stream().map(String::toLowerCase);

Stream<String> firstLetters = words.stream().map(s -> s.substring(0,1));

//char 값이 두개 필요한 유니코드 문자를 올바르게 처리한다.
public static Stream<String> codePoints(String s) {
List<String> result = new ArrayList<>();
int i = 0;
while(i < s.length()) {
int j = s.offsetByCodePoints(i, 1);
result.add(s.substring(i, j));
i = j;
}
return result.stream();
}

Stream<Stream<String>> result = words.stream().map(w -> codePoints(w));


결과 
[... ["y", "o", "u", "r"], ["b", "o", "a", "t"],...]
이 스트림을 단일 스트림 [..."y", "o", "u", "r""b", "o", "a", "t",...]으로 펼치려면 map 대신 flatMap 메서드를 사용해야 한다.

Stream <String> flatResult = words.stream(). flatMap(w -> codePoints(w));


서브 스트림 추출과 스트림 결합 
limit() 요소 n개 이후 끝나는 새 스트림을 반환한다.
Stream <Double> words = Stream.of(contents.split("\\PL")). limit(100)

skip() limit와의 반대 작업을 수행, n개의 요소를 버린다.
Stream <String> randoms = Stream.of(contents.split("\\PL+")). skip(1);

takeWhile(predicate) 호출은 프레디 케이트가 참 인동 안 스트림에서 모든 요소를 가져온 후 중단
stream <String> initialDigits = codePoints(str). takeWhile(s -> "0123456789". contents(s));

dorpWhile 메서드는 반대로 조건이 참인 동안 요소를 버리고, 조건이 처음 거짓으로 판명된 요소부터 시작해 모든 요소의 스트림을 돌려줌 
Stream <String> withoutInitialWhiteSpace = codePoints(str). dropWhile(s -> s.trim(). length() == 0);

concat 스트림을 연결할 수 있다. 
Stream <String> combined = Stream.concat(codePoint("Hello"), codePoints("World"));
//스티림 ["H", "E", "L", "L", "O", "W",,,,,]


스트림 변환 
distinct 메서드는 원본 스트림에 있는 요소의 중복을 제외하고 같은 순서로 되돌려주는 스트림을 반환 

Stream <String> uniqueWords =  Stream.of("merrily", "merrily", "merrily", "gently"). distinct();
//merrily를 한 개만 보존

스트림 정렬용 sorted
Stream <String> longFrist = words.stream(). sorted(Comparator.comparing(String::length)). reversed();


단순 리덕션 결과를 얻는 방법)
리덕션 - 종료 연산 
count(), max(), min()

주의할 점은 Optional <T> 값으로 반환한다. 
Optional <T> 값은 결과를 감싸고 있거나 결과가 없음을 나타낸다. 
반환 값이 빠진 상황을 가리킬 때는 optional 타입을 쓰는 것이 좋다. 

max() 최댓값 얻기
Optional <String> largest = words.max(String::compareToIgnoreCase);
System.out.println("" + largest.orElse(""));

findFirst() 첫 번째 값을 반화
Optional <String> startsWithQ = words.filter(s -> s.startWith("Q")). findFirst();

findAny 어떤 일치 결과가 나오든 상관없을 때 
스트림을 병렬화 할 때 유리
Optional <String> startWithQ = words.parallel(). filter(s -> s.startWith("Q")). findAny();

anyMatch 단순히 일치하는 요소 
boolean aWordStartsWithQ = words.parallel(). anyMatch(s -> s.startWith("Q"));

allMatch 모든 요소가 일치함
noneMatch 모든 요소가 일치하지 않음

Optional 
값이 없을 때는 대체 값을 생산하고, 값이 있을 때는 해당 값을 소비하는 메서드를 사용

String result = optinalString.orElse("");
//옵션 값으로 래핑 된 문자열 또는 없으면 ""

optionalString.orElseGet(() -> System.getProperty("myapp.default"));
//필요할 때만 함수가 호출