스트림을 사용 하여 다음과 같은 2차원 배열에서 문자열의 길이가 4이상인 요소들만 출력
java | c# | python |
mysql | oracle | msql |
php | asp | jsp |
intelliJ | Eclipse |
스트림 사용
방법1. 익명객체
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class FlatMapExample {
public static void main(String[] args) {
String[][] array = {
{"java","C#","python"},
{"mysql","oracle","msql"},
{"php","asp","jsp"},
{"intelliJ","Eclipse"},
};
Arrays.stream(array) // 2차원 배열의 스트림
.flatMap(
new Function<String[], Stream<?>>() {
@Override
public Stream<?> apply(String[] strings) {
return Arrays.stream(strings); // 1차원 배열의 스트림
}
}
).filter(new Predicate<Object>() {
@Override
public boolean test(Object o) {
return ((String)o).length()>=4; // 길이가 4인 객체들만 필터링
}
}
).forEach(System.out::println);
}
}
방법2. 람다식
package Chap35.Stream.Exam05;
import java.util.Arrays;
public class FlatMapExample {
public static void main(String[] args) {
String[][] array = {
{"java","C#","python"},
{"mysql","oracle","msql"},
{"php","asp","jsp"},
{"intelliJ","Eclipse"},
};
Arrays.stream(array)
.flatMap(s -> Arrays.stream(s))
.filter(o -> o.length()>=4) //응?? 형변환 안해도되네??
.forEach(System.out::println); //이거 아는사람 좀 알려주세요ㅠ
}
}
방법3. 메소드 참조
package Chap35.Stream.Exam05;
import java.util.Arrays;
public class FlatMapExample {
public static void main(String[] args) {
String[][] array = {
{"java","C#","python"},
{"mysql","oracle","msql"},
{"php","asp","jsp"},
{"intelliJ","Eclipse"},
};
Arrays.stream(array)
.flatMap(Arrays::stream)
.filter(FlatMapExample::test)
.forEach(System.out::println);
}
private static boolean test(String o) {
return o.length() >= 4;
}
}
결론 : 이렇게 사용하자.
Arrays.stream(array)
.flatMap( Arrays::stream)
.filter( o -> o.length()>=4)
.forEach(System.out::println);
사실 이중for문으로 쉽게 할수 있음
public class FlatMapExample {
public static void main(String[] args) {
String[][] array = {
{"java","C#","python"},
{"mysql","oracle","msql"},
{"php","asp","jsp"},
{"intelliJ","Eclipse"},
};
for(String[] arr : array){
for(String e : arr){
if(e.length()>=4) System.out.println(e);
}
}
}
}
[Collection : List] 배열 병합 addAll() (0) | 2020.06.17 |
---|---|
[System] 배열 병합 arraycopy(src,srcPos,dest,length) 예제 (0) | 2020.06.17 |
[Stream] 스트림 중복 제거 : distinct() 메서드 예제 (0) | 2020.06.17 |
[Stream] 스트림 필터 : filter() 메서드 예제 (0) | 2020.06.17 |
[Stream] 배열에서 스트림 얻기 (0) | 2020.06.16 |
댓글 영역