int max(int a, int b){
return a > b ? a : b;
}
(a,b) -> a > b ? a : b;
@FunctionalInterface
interface CustomInterface<T> {
// abstract method 오직 하나
T myCall();
}
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
-------- (람다식)
( ) --> void
@FunctionalInterface
public interface Supplier<T> {
T get();
}
-------- (람다식)
( ) --> T
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
-------- (람다식)
T --> void
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
-------- (람다식)
T --> R
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
-------- (람다식)
T --> boolean
void accept(Integer i, Integer i2)
-------- (람다식)
(i,i2) -> void
boolean test(Integer i, Integer i2)
-------- (람다식)
(i,i2) -> boolean
int apply(Integer i, Integer i2)
-------- (람다식)
(i,i2) -> int i3
interface StatementStrategy{
boolean compare(int a, int b);
}
public class SelectionSort2 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public int[] solution(int[] arr,StatementStrategy stmt){
int[] result = arr;
for(int i=0; i<arr.length; i++){
int minidx = i;
for(int j=i; j<arr.length; j++){
if(stmt.compare(result[minidx],result[j])) // interface를 통해 값만 구현후 원하는 식에 넣어 사용
minidx = j;
}
int temp = result[i];
result[i] = result[minidx];
result[minidx] = temp;
}
return result;
}
public static void main(String[] args) throws IOException {
SelectionSort2 s = new SelectionSort2();
String[] temp = br.readLine().split(" ");
int[] arr = new int[temp.length];
for(int i=0; i<temp.length; i++){
arr[i] = Integer.parseInt(temp[i]);
}
System.out.println(Arrays.toString(s.solution(arr,(a,b) -> a>b)));
System.out.println(Arrays.toString(s.solution(arr,(a,b) -> a<b)));
// int[] r = s.solution(arr, new StatementStrategy() {
// @Override
// public boolean compare(int a, int b) {
// return a>b;
// }
// });
}
}
public class SelectionSort3 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public int[] solution(int[] arr, BiFunction<Integer,Integer,Boolean> stmt){
int[] result = arr;
for(int i=0; i<arr.length; i++){
int minidx = i;
for(int j=i; j<arr.length; j++){
if(stmt.apply(arr[minidx],arr[j])) // apply 결과값이 참일때 동작함
minidx = j;
}
int temp = result[i];
result[i] = result[minidx];
result[minidx] = temp;
}
return result;
}
public static void main(String[] args) throws IOException {
SelectionSort3 s = new SelectionSort3();
System.out.print("정렬할 값들을 입력하세요 :");
String[] temp = br.readLine().split(" ");
int[] arr = new int[temp.length];
for(int i=0; i<temp.length; i++){
arr[i] = Integer.parseInt(temp[i]);
}
BiFunction<Integer,Integer,Boolean> biFunction = (a,b) -> a>b;
BiFunction<Integer,Integer,Boolean> biFunction2 = (a,b) -> a<b;
System.out.println(Arrays.toString(s.solution(arr,biFunction)));
System.out.println(Arrays.toString(s.solution(arr,biFunction2)));
}
}
참고자료 : 자바의 정석