100일 챌린지/빅데이터기반 인공지능 융합 서비스 개발자
Day 75 - interface, lamda식, stream
ksyke
2024. 11. 14. 12:46
Lamda
jdk 1.8 ver 부터 등장한 새로운 문법
javascript의 arrow function을 본따서 만들었다.
// javascript arrow function : var func=(a,b)=>{return ;}
// java lamda 함수 (하나의 메소드를 갖고 있는 인터페이스만 가능)
Runnable func=()->{
System.out.println("my thread:"+Thread.currentThread().getName());
};
Thread thr=new Thread(func);
thr.start();
System.out.println("main:"+Thread.currentThread().getName());
Functional interface
@FunctionalInterface
interface Inter{
void func();
}
lamda식을 만들기 위한 annotation. 해당 어노테이션이 붙어있지 않더라도 메소드가 한개이면 람다함수로 사용 가능하다.
void func01(Inter inter,int su) {
inter.test(a,b);
}
void func02(Inter03 inter,int a,int b) {
inter.test(su);
}
int func03(Comparable inter,String msg) {
return inter.compareTo(msg);
}
@FunctionalInterface
interface Inter{
void test(int a);
}
@FunctionalInterface
interface Inter02{
int test();
}
@FunctionalInterface
interface Inter03{
int t
}
@Override
public void run(String... args) throws Exception {
Inter inter=(su)->{};
func01(inter,4321);
Inter02 inter02=()->{return 33;};
final int a=1111;
Inter02 inter03=()->{return a;};
Inter02 inter04=()->a;
Inter03 inter05=(x,y)->{return x+y;};
Inter03 inter06=(x,y)->x+y;
func02((x,y)->x*y,1,2);
func03(o -> 1234,"test");
}
Interface
@FunctionalInterface
public interface Inter04 {
void func01();
public static void func02() {
System.out.println("func02 run...");
}
public default void func03() {
System.out.println("func03 run...");
}
}
Inter04 inter07=new Inter04() {
@Override
public void func01() {
System.out.println("func01 run...");
}
};
Inter04 inter08=()->{System.out.println("func01 run...");};
inter07.func01();
Inter04.func02();
inter07.func03();
// 매개변수 o, 리턴 x
Consumer test1=(x)->System.out.println(x);
// 매개변수 x, 리턴 o
Supplier test2=()->1234;
// 매개변수 o, 리턴 o
Function test3=(x)->x;
// 매개변수 o o, 리턴 o
IntBinaryOperator test4=(x,y)->x+y;
DoubleBinaryOperator test6=(x,y)->x+y;
// 매개변수 o, 리턴 o(t/f)
Predicate test5=(x)->true;
Stream
stream 생성 -> 처리 -> 취합(결론)
stream 생성
// Stream 생성
Stream<String> stream1=Stream.of("item1","item2","item3","item4");
stream1.forEach(s -> System.out.println(s));
Stream<Integer> stream2=Stream.of(1,2,3,4);
Stream<String> stream3=Stream.empty();
List list=List.of("item1","item2","item3","item4");
Stream<String> stream4=list.stream();
String[] arr= {"item1","item2","item3","item4"};
Stream<String> stream5=Arrays.stream(arr);
Stream<String> stream6=Stream.generate(() ->"item").limit(4);
System.out.println("stream 생성하겠습니다.");
Stream<Integer> stream7=Stream.iterate(0,n -> n+2).limit(5);
System.out.println("stream 생성되었습니다.");
System.out.println("stream 실행하겠습니다.");
Stream<String> stream8=Stream.iterate("item",n -> n+1).limit(5);
stream8.forEach(s -> System.out.println(s));
System.out.println("stream 실행되었습니다.");
Stream<String> stream9=Stream.<String>builder()
.add("item1")
.add("item2")
.add("item3")
.add("item4")
.build();
IntStream intStream=IntStream.range(1, 5); // [1,2,3,4]
LongStream longStream=LongStream.rangeClosed(1, 5); // [1,2,3,4,5]
Stream<Integer> boxedIntStream=IntStream.range(1, 5).boxed();
boxedIntStream.forEach(s -> System.out.println(s));
DoubleStream doubles=new Random().doubles(3);
doubles.forEach(s -> System.out.println(s));
IntStream charsStream="Stream".chars();
Stream<String> stringStream=Pattern.compile(",").splitAsStream("item1,item2,item4");
stringStream.forEach(s -> System.out.println(s));
Stream 가공
stream = stream.map(msg->"<li>"+msg+"</li>");
intStream=intStream.map(su->su*2);
intStream=intStream.filter(su->su%2!=0);
stream=stream.distinct();
stream=stream.sorted();
stream=stream.sorted((o1, o2) -> o2.compareTo(o1));
stream=stream.peek(msg->System.out.println("---------"));
stream=stream.sorted(String::compareTo);
stream=stream.peek(msg->System.out.println("---------"));
stream.forEach(System.out::println);
int sum=IntStream.range(1, 5)
.peek(i->System.out.println("before확인:"+i))
.sorted()
.map(i->{System.out.println("after확인:"+i); return i;})
.sum();
System.out.println("합계:"+sum);
List<String> numbers = Arrays.asList("1", "2", "3", "4", "5");
List<String> chars = Arrays.asList("a", "b", "c", "d", "e");
Stream<String> stream1 = numbers.stream();
Stream<String> stream2 = chars.stream();
Stream<String> stream3 = Stream.concat(stream1, stream2);
Stream 취합
ArrayList<String> data=new ArrayList<>();
stream3.forEach(msg->data.add(msg));
Optional<String> data=stream3.reduce((x,y) -> x+y);
System.out.println(data);
double sum=IntStream.range(1, 5)
.reduce((x,y) -> x+y).getAsInt();
.sum();
.average().getAsDouble();
.count();
.max().getAsInt();
.min().getAsInt();
System.out.println("합계:"+sum);
int[] intArr = { 2, 4 ,6 };
boolean result = Arrays.stream(intArr)
.allMatch(a -> a%2==0);
System.out.println("모두 2의 배수인가? " + result);
result = Arrays.stream(intArr)
.anyMatch(a -> a%3==0);
System.out.println("하나라도 3의 배수가 있는가? " + result);
result = Arrays.stream(intArr)
.noneMatch(a -> a%3==0);
System.out.println("3의 배수가 없는가? " + result);
List<String> list = stream.collect(Collectors.toList());
System.out.println(list);
Set<String> set = stream.collect(Collectors.toSet());
System.out.println(set);
Map<String, String> map = stream.collect(
Collectors.toMap(k -> k, v -> v.substring(4))
);
System.out.println(map);
String joined = stream.collect(Collectors.joining(","));
String joined = stream.collect(Collectors.minBy(Comparator.naturalOrder())).get();
String joined = stream.collect(Collectors.maxBy(Comparator.naturalOrder())).get();
System.out.println(joined);
stream = Stream.of("apple", "banana", "cherry", "date");
Map lengGroup =
stream.collect(Collectors.groupingBy(t -> t.contains("a")));
System.out.println(lengGroup);
Optional
null이 떨어지는 현상을 해결하기 위해 만들어짐
String string = "a string in optional";
Optional<String> opString = Optional.of(string);
System.out.println(opString.get());
// Optional.of(null) 불가
Optional<String> nullOpString = Optional.ofNullable(null);
Optional<String> emptyOptional = Optional.empty();
try {
System.out.println(nullOpString.get());
} catch (NoSuchElementException e) {
System.out.println("No such element");
}
System.out.println(emptyOptional.isPresent());
String name = emptyOptional.orElse("anonymous");
System.out.println(name);