간단이론정리/JAVA

about Java 8

눕고싶은사람 2024. 6. 11. 18:20

Java 8은 2014년 3월에 공개되었다.

3가지의 LTS(Long Term Support) 버전 중 하나이다.

  • Java 8
  • Java 11
  • Java 17

LTS 버전은 말 그대로 오랜 기간 지원을 해주기 때문에 실제 개발 시 사용하기에 용이하다.


 

23년 기준 Java 8 채택률은 약 50% (출처 : jetbrains)

 

일반 지원은 2019년 종료 되었지만, 연장 지원은 2023년 9월까지 였다.

 

여전히 많이 사용되어지고 있는 Java 8의 특징을 보려고 한다.


Java 8에 추가 된 내용

  • 람다 표현식(Lambda Expression)
  • 메서드 참조(Method Reference)
  • Interface의 Default Method
  • Optional
  • Stream
  • 새로운 시간/날짜 API

 

1. 람다 표현식 (Lambda Expression)

익명 함수의 개념을 가져와 메소드를 하나의 식으로 표현하여 편의성을 제공함

 

1-1. 예제

List<String> nameList = Arrays.asList("A", "B", "C", "D", "E");

//일반 반복문
for(String name : nameList) {
    System.out.println(name);
}

//람다
nameList.forEach(x -> System.out.println(x));

 

2. 메서드 참조(Method Reference)

람다의 축약 표현

 

2-1. 예제

 

List<String> nameList = Arrays.asList("A", "B", "C", "D", "E");

//람다
nameList.forEach(x -> System.out.println(x));

//메서드
nameList.forEach(System.out::println);

 

3. Interface의 Default Method

인터페이스에서 default 메소드로 구현체를 만들 수 있다.(+static)

 

3-1. 예제

public interface defaultInterface {
	default int addDefault(int x) {
    	return x+1;
    }
    
    static int addStatic(int x) {
    	return x+1;
    }
}

 

4. Optional

NPE(Null Pointer Exception) 방지를 위해 도입된 기능

DB 조회 결과를 검증 할 때 유용하다.

 

4-1. 예제

Optional<MemberVO> memberInfo = memberRepository.findByMemberName(memberName);
//이 경우 repository에 Optional로 findByMemberName을 생성해둠.

if(memberInfo.isPresent()) {
//검증
} else {}

 

5. Stream

데이터 컬렉션을 함수형 스타일로 처리 할 수 있게 해주는 기능.

대용량 데이터 처리에 있어서 성능 향상.

 

5-1. 예제

List<String> nameList = Arrays.asList("Alpha", "Beta", "Charlie", "Delta", "Echo");

//길이 5 이상 필터링
List<String> nameFilterList = nameList.stream()
.filter(x -> x.length() >= 5)
.collect(Collectors.toList());

System.out.println(nameFilterList); //Alpha, Charlie, Delta

------------------------------------------------------------------------------------------

List<String> highScoreMember = 
                members.stream()
                    .filter(x -> x.getScore() > 80)		//80점 이상인 멤버들 추출
                    .sorted(comparing(Member::getScore))	//점수 순 정렬
                    .map(Membmer::getName)			//멤버 이름 추출
                    .collect(Collectors.toList());		//리스트로 만듬

 

 

6. 새로운 시간/날짜 API

기존 제공하던 Date 클래스의 모호한 설계로 인해 문제가 있었고

새로운 LocalDate, LocalTime, LocalDateTime, OffsetDateTime 등의 클래스가 추가 되었다.

 

6-1. 예제

LocalDate localDate = LocalDate.now();

System.out.println(localDate.getDayOfWeek().toString()); //WEDNESDAY
System.out.println(localDate.getDayOfMonth());           //15
System.out.println(localDate.getDayOfYear());            //135
----------------------------------------------------------------------------
LocalTime localTime = LocalTime.of(12, 20);

System.out.println(localTime.toString());    //12:20
System.out.println(localTime.getHour());     //12
System.out.println(localTime.getMinute());   //20
System.out.println(localTime.getSecond());   //0
System.out.println(localTime.MIDNIGHT);      //00:00
System.out.println(localTime.NOON);          //12:00
----------------------------------------------------------------------------
LocalDateTime localDateTime = LocalDateTime.now();

System.out.println(localDateTime.toString());      //2024-06-01T10:01:14.911
System.out.println(localDateTime.getDayOfMonth()); //01
System.out.println(localDateTime.getHour());       //10
System.out.println(localDateTime.getNano());       //911000000
----------------------------------------------------------------------------
OffsetDateTime offsetDate = OffsetDateTime.now();
System.out.println(offsetDate); //2024-05-27T15:10:46.260589600+05:30

 

출처 및 참고

https://incheol-jung.gitbook.io/docs/q-and-a/java/jdk-8#lambda-expressions

 

JDK 8 특징 | Incheol's TECH BLOG

JDK 8 특징을 알아보자

incheol-jung.gitbook.io

https://seoarc.tistory.com/102

 

[Java] Java 8 특징

Java SE 8 (LTS) 2014년 3월에 공개했으며 대표적인 변경 사항은 다음과 같다. 람다 표현식(Lambda Expression) 람다 표현식은 메서드로 전달할 수 있는 익명 함수를 단순화한 것이다. 람다 표현식에는 이름

seoarc.tistory.com

https://velog.io/@skyepodium/%EC%9E%90%EB%B0%94-Java-8-%EB%B2%84%EC%A0%84-%ED%8A%B9%EC%A7%95#1-%EA%B0%9C%EC%9A%94

 

[자바] Java 8 버전 특징

Java 8 버전 특징

velog.io

 

'간단이론정리 > JAVA' 카테고리의 다른 글

가비지 컬렉션 (GC, Garbage Collection) (1)  (0) 2024.06.15
about Java 17  (0) 2024.06.13
about Java 11  (0) 2024.06.13
JAVA의 Wrapper Class와 Boxing & UnBoxing  (0) 2024.06.12
JAVA 변수의 기본형 & 참조형 정리  (0) 2024.06.12