: 자료의 대상과 관계없이 동일한 연산 수행
: 배열, 컬렉션을 대상으로 연산 수행
System.out.println();
sList.stream().map(s->s.length()).forEach(n->System.out.print(n+"\t"));
System.out.println();
sList.stream().filter(s->s.length() >= 5).forEach(s->System.out.println(s));
//람다식에는 익명클래스가 숨어져있다.
}
}
한번 생성하고 사용한 스트림은 재사용이 불가하다.
👉 다른 연산 수행하기위해 스트림을 다시 생성하는걸 볼 수 있음
스트림 연산은 중간연산과 최종연산으로 구분
👉 상기 코드에서 map(), filter()와 같은게 중간 연산, forEach가 최종 연산 이다.
👉 중간 연산은 여러개 연산이 적용될 수 있지만 최종 연산은 마지막에 한번만 적용된다.
👉 최종 연산이 호출되어야 중간 연산의 수행이 이뤄지며 중간 연산의 결과를 연산중에 알수없다. (=지연 연산)
public class TravelCustomerTest {
public static void main(String[] args) {
TravelCustomer customerLee = new TravelCustomer("이순신", 40, 100);
TravelCustomer customerKim = new TravelCustomer("김유신", 20, 100);
TravelCustomer customerHong = new TravelCustomer("홍길동", 13, 50);
List<TravelCustomer> customerList = new ArrayList<TravelCustomer>();
customerList.add(customerLee);
customerList.add(customerKim);
customerList.add(customerHong);
System.out.println("고객 명단 출력");
customerList.stream().map(c->c.getName()).forEach(s->System.out.println(s));
System.out.println("여행 비용 출력");
System.out.println(customerList.stream().mapToInt(c->c.getPrice()).sum());
System.out.println("20세 이상 고객의 이름 정렬");
customerList.stream().filter(c -> c.getAge() >= 20).map(c->c.getName()).sorted().forEach(s->System.out.println(s));
//조건 거를때 filter사용, 정렬은 sorted사용. 다만 정렬 솔티드 이용한다해도 기존 배열이 바뀌는것 은 아님.
"고객 명단 출력"에서 map()을 이용하여 Name항목만 불러올 수 있다.
map()을 사용하지 않으면 toString이 전부 불려온다.
(int값으로 불러온다면 mapToInt 사용)
20세 이상과 같은 조건을 걸고싶다면 filter()이용, 정렬하고싶다면 sorted()를 이용한다.
👉 sorted()를 이용한다고 해서 정렬된 그대로 기존자료까지 변경되는 것은 아니다.
👉 스트림 연산은 스트림용 메모리 공간이 별도로 생성되기때문에 기존자료를 변경하지 않는다.
: 프로그램을 만들다보면 발생하는 오류를 무시하거나 적절하게 처리하고 싶을 때 사용
: 예외처리를 해주면 보다 안전하고 유연한 프로그래밍을 구사 할 수 있다.
public class AutoCloseableObj implements AutoCloseable{
@Override
public void close() throws Exception {
System.out.println("closing....");
}
}
상속코드
public class AutoCloseableTest {
public static void main(String[] args) {
AutoCloseable obj = new AutoCloseableObj() ;
try(obj) {
throw new Exception();
}catch(Exception e) {
System.out.println("exception");
}
System.out.println("end");
}
}
public class ThrowsException {
public Class loadClass(String fileName, String className) throws ClassNotFoundException, FileNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
Class c = Class.forName(className);
return c;
}
public static void main(String[] args) {
ThrowsException test = new ThrowsException();
try {
test.loadClass("a.txt", "java.lang.String");
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (FileNotFoundException e) {
System.out.println(e);
} catch(Exception e) {
}
System.out.println("end");
}
}
throws (예외 미루기, 예외 던지기)
👉 Exception을 발생시킨 메서드가 아닌 main메서드에서 처리하도록 미루는 것
👉 프로그래밍 시 예외를 처리하는 위치가 중요하기 때문에 때와 상황에 따라 예외를 처리할 메서드를 신중하게 고려해야한다.
default exception은 맨 마지막에 위치해야한다.