반응형
- stream, filter, predicate 사용 예제
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Playground {
public static List<String> friends = Arrays.asList("taewon", "brian", "timmy", "turner", "ed", "edd", "eddy", "samuel", "jackson", "miranda", "Samantha", "sarah");
public static void main(String[] args) {
List<String> startsWithT = friends.stream()
.filter(checkIfStartsWith("t"))
.collect(Collectors.toList());
List<String> startsWithE = friends.stream()
.filter(checkIfStartsWith("e"))
.collect(Collectors.toList());
}
public static Predicate<String> checkIfStartsWith(String letter) {
return name -> name.startsWith(letter);
}
}
- 총 길이 찾기
import java.util.Arrays;
import java.util.List;
public class Playground {
public static List<String> friends = Arrays.asList("taewon", "brian", "timmy", "turner", "ed", "edd", "eddy", "samuel", "jackson", "miranda", "Samantha", "sarah");
public static void main(String[] args) {
int sum = friends.stream()
.mapToInt(name -> name.length())
.sum();
}
}
- 긴 이름 기준 조건으로 이름 찾기, optional
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Playground {
public static List<String> friends = Arrays.asList("taewon", "brian", "timmy", "turner", "ed", "edd", "eddy", "samuel", "jackson", "miranda", "Samantha", "sarah");
public static void main(String[] args) {
Optional<String> longestName = friends.stream()
.reduce((name1, name2) -> name1.length() >= name2.length() ? name1 : name2);
longestName.ifPresent(System.out::println);
}
}
출처 :
반응형