[JAVA8] IntStream , Lamda 활용
IntStream과 람다식 응용하기
import java.util.Collections; import java.util.List; import java.util.function.IntPredicate; import java.util.stream.Collectors; import java.util.stream.IntStream; class IntStream_Ex { public static void main(String[] args) { IntStream.range(0, 10).forEach((int value) -> System.out.println(value)); System.out.println("MAX with Lamda: "+IntStream.range(0, 10).max().getAsInt()); int a = 0; int b = 10; IntPredicate predicate = i -> i >= 0; // 모든 엘리먼트 조건식 검사 > boolean 리턴 System.out.println(IntStream.range(a, b).allMatch(predicate)); // 하나라도 조건식 맞는지 검사 > boolean 리턴 IntPredicate predicate2 = i -> i < 0; System.out.println(IntStream.range(a, b).anyMatch(predicate2)); // 평균값 System.out.println(IntStream.range(a, b).average()); // Stream<Intger> 형태로 변환 System.out.println(IntStream.range(a, b).boxed().toArray()[0]); // 스크림 갯수 반환 System.out.println(IntStream.range(a, b).count()); // Stream내 중복제거 IntStream stream = IntStream.of(1,1,2,2,3,3); stream.distinct().forEach((int value) -> System.out.println(value)); System.out.println(); //필터링 조건걸기 IntStream.range(a,b).filter(i -> i>=5).forEach((int value) -> System.out.println(value)); System.out.println(); int[] unSortedInt = {1,3,2,5,4}; // 소팅하기(오름차순) IntStream.of(unSortedInt).sorted().forEach((int value) -> System.out.println(value)); // 소팅하기(역순) IntStream.of(unSortedInt).boxed().sorted(Collections.reverseOrder()).forEach(System.out::println); System.out.println("===== IntStream > Array ====="); // Array로 변환 int[] intArr = IntStream.of(unSortedInt).sorted().toArray(); for(int i=0; i< intArr.length; i++){ System.out.println(intArr[i]); } // List로 변환 System.out.println("===== IntStream > List ====="); List<Integer> arrList = IntStream.of(unSortedInt).sorted().boxed().collect(Collectors.toList()); arrList.forEach(i -> { System.out.print(i); System.out.println(""); }); } }
최근 댓글