Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- 빅데이터
- 코딩독학
- backend
- 자바독학
- 사물인터넷
- java
- Project
- 이웃한 칸
- 프로그래머스
- 자바
- java정리
- 코스닥
- 자바정리
- 풀스택프레임워크
- Python
- 코테
- 개인프로젝트
- 주가예측
- 개발
- 프로그램
- 모의 주식
- SNS
- 프로그래밍
- 백준
- frontend
- C++
- 코딩테스트
- 개발자
- Reflex
- 코딩
Archives
- Today
- Total
Creative Code
람다 함수,stream 본문
람다함수 기본 사용법
@FunctionalInterface //람다함수로 사용할 인터페이스에 써준다
interface Calculator { //람다를 쓸때에는 매서드를 2개이상 입력할수 없다)
int sum(int a, int b , int c);
}
public class Main {
public static void main(String[] args) {
Calculator mc = (a,b,c) -> a+b+c; // 람다적용
int result = mc.sum(3,4,5);
System.out.println(result);
}
}
**BiFunction(람다함수의 인수가 2개일때)
import java.util.function.BiFunction; // 람다함수의 인수가 2개일때사용
public class Main {
public static void main(String[] args) {
BiFunction<Integer,Integer,Integer>mc = (a,b) -> a+b; //앞의 integer 2개는 입력자료형 , 뒤에 1개는 출력자료형이다.
int result = mc.apply(3,4); //BiFunction은 apply를 쓴다.
System.out.println(result);
}
}
**BinaryOperator
import java.util.function.BinaryOperator;
public class Main {
public static void main(String[] args) {
BinaryOperator<Integer>mc = (a,b) -> a+b; // 입력자료형과 출력자료형이 모두 동일하면 BinaryOperator 을 쓴다.
int result = mc.apply(3,4);
System.out.println(result);
}
}
**stream
import java.util.Arrays;
import java.util.Comparator;
public class Sample {
public static void main(String[] args) {
int[] data = {5, 6, 4, 2, 3, 1, 1, 2, 2, 4, 8};
int[] result = Arrays.stream(data) // IntStream을 생성한다.
.boxed() // IntStream을 Stream<Integer>로 변경한다.
.filter((a) -> a % 2 == 0) // 짝수만 걸러낸다.
.distinct() // 중복을 제거한다.
.sorted(Comparator.reverseOrder()) // 역순으로 정렬한다.
.mapToInt(Integer::intValue) // Stream<Integer>를 IntStream으로 변경한다.
.toArray() // int[] 배열로 반환한다.
;
}
}