자바 8 java.time.temporal. TemporalAdjusters 및 Stream.flatMap() 자습서
게시 됨: 2020-09-09
2014년 3월에 Java 8이 출시된 지 거의 2년이 되었습니다. 대부분의 회사가 여전히 프로덕션 환경에서 Apache Tomcat과 함께 Java 7을 사용하고 있다고 확신하지만 최근에는 약간의 추진력을 얻고 있습니다.
대부분의 회사가 여전히 Java 7을 사용하고 있기 때문에 세계에서 주목받지 못하는 기능이 꽤 있습니다.
언젠가 Java 8 Stream API 및 Lambda 표현식에 대한 자세한 기사를 작성했습니다. 이 튜토리얼에서는 java.time.temporal.TemporalAdjusters
및 flatMap()
예제를 살펴보겠습니다.
임시 객체
Java에서 tempoalObjects
는 무엇입니까? 날짜 및 시간 개체, 주로 generic manner
액세스를 제공하는 read-only objects
를 처리하는 프레임워크 수준 인터페이스입니다.
시간 조정자
TemporalAdjusters는 임시 개체를 수정하기 위한 핵심 도구입니다. TemporalAdjuster를 사용할 수 있는 두 가지 방법이 있습니다.
- 인터페이스에서 직접 메소드 호출
- Temporal.with(TemporalAdjuster) 사용

Stream.flatMap()
Java map
과 flatMap
은 Stream<T>
에 적용할 수 있으며 둘 다 Stream<R>
을 반환합니다. 차이점은 무엇입니까?
-
map
연산은 각 입력 값에 대해 하나의 출력 값을 생성합니다. -
flatMap
작업은 각 입력 값에 대해 임의의 수(0개 이상) 값을 생성합니다.
튜토리얼을 시작해 봅시다
- CrunchifyJava8TemporalAdjustersAndFlatMap.java 클래스 생성
- 우리는 두 가지 간단한 방법을 만들 것입니다
- crunchifyStreamFlatMap예제
- crunchifyTemporalExample
- 모든 세부 정보는 각 방법 자체에 주석으로 제공됩니다.
- 프로그램 실행 및 결과 확인
- Eclipse 환경에서 JDK 8을 설정했는지 확인하십시오.
CrunchifyJava8TemporalAdjustersAndFlatMap.java
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
package crunchify . com . tutorials ; import java . time . DayOfWeek ; import java . time . LocalDateTime ; import java . time . temporal . TemporalAdjusters ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import java . util . stream . Collectors ; /** * @author Crunchify.com * Java 8 java.time.temporal. TemporalAdjusters and Stream.flatMap() Tutorial */ public class CrunchifyJava8TemporalAdjustersAndFlatMap { public static void main ( String [ ] args ) { // Stream.flatMap() example crunchifyStreamFlatMapExample ( ) ; // TemporalAdjuster example crunchifyTemporalExample ( ) ; } public static void crunchifyStreamFlatMapExample ( ) { List <CrunchifyCompany> companyList = new ArrayList < > ( ) ; CrunchifyCompany gName = new CrunchifyCompany ( "Google" ) ; gName . add ( "Gmail" ) ; gName . add ( "Docs" ) ; gName . add ( "Google Apps" ) ; CrunchifyCompany yName = new CrunchifyCompany ( "Yahoo" ) ; yName . add ( "YMail" ) ; yName . add ( "Yahoo Sites" ) ; companyList . add ( gName ) ; companyList . add ( yName ) ; // Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped // stream produced by applying the provided mapping function to each element crunchifyLog ( "Here is a list of all Company product list:" ) ; List <String> crunchifyList = companyList . stream ( ) . flatMap ( element - > element . getProducts ( ) . stream ( ) ) . collect ( Collectors . toList ( ) ) ; crunchifyLog ( crunchifyList . toString ( ) ) ; } private static void crunchifyLog ( String msg ) { System . out . println ( msg ) ; } static class CrunchifyCompany { private String companyName ; private final Set <String> products ; public CrunchifyCompany ( String companyName ) { this . setCompanyName ( companyName ) ; this . products = new HashSet < > ( ) ; } public void add ( String animal ) { // add(): Adds the specified element to this set if it is not already present (optional operation). // More formally, adds the specified element e to this set if the set contains no element e2 such that Objects.equals(e, e2). // If this set already contains the element, the call leaves the set unchanged and returns false. this . products . add ( animal ) ; } public Set <String> getProducts ( ) { return products ; } public String getCompanyName ( ) { return companyName ; } public void setCompanyName ( String companyName ) { this . companyName = companyName ; } } public static void crunchifyTemporalExample ( ) { // A date-time without a time-zone in the ISO-8601 calendar system // String time = LocalDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); // Let's return currentitme - 1 year LocalDateTime crunchifyTime = LocalDateTime . now ( ) . minusYears ( 1 ) ; // TemporalAdjusters: Adjusters are a key tool for modifying temporal objects crunchifyLog ( "\n- get 1st Day of Month: " + crunchifyTime . with ( TemporalAdjusters . firstDayOfMonth ( ) ) ) ; // Returns the "last day of month" adjuster crunchifyLog ( "- get Last Day of Month: " + crunchifyTime . with ( TemporalAdjusters . lastDayOfMonth ( ) ) ) ; // Returns the "first day of year" adjuster crunchifyLog ( "- get 1st Day of Year: " + crunchifyTime . with ( TemporalAdjusters . firstDayOfYear ( ) ) ) ; // Returns the next day-of-week adjuster crunchifyLog ( "- get next Day Of Week: " + crunchifyTime . with ( TemporalAdjusters . next ( DayOfWeek . WEDNESDAY ) ) ) ; // Returns the "last day of year" adjuster crunchifyLog ( "- get last Day of Year: " + crunchifyTime . with ( TemporalAdjusters . lastDayOfYear ( ) ) ) ; // Returns the last in month adjuster crunchifyLog ( "- get last Day Of Week: " + crunchifyTime . with ( TemporalAdjusters . lastInMonth ( DayOfWeek . FRIDAY ) ) ) ; } } |
산출:
다음은 콘솔 결과입니다. 위의 Java 프로그램을 실행하면 아래와 같은 결과를 볼 수 있습니다.

1 2 3 4 5 6 7 8 9 |
Here is a list of all Company product list : [ Gmail , Docs , Google Apps , YMail , Yahoo Sites ] - get 1st Day of Month : 2015 - 01 - 01T12 : 07 : 11.980 - get Last Day of Month : 2015 - 01 - 31T12 : 07 : 11.980 - get 1st Day of Year : 2015 - 01 - 01T12 : 07 : 11.980 - get next Day Of Week : 2015 - 01 - 14T12 : 07 : 11.980 - get last Day of Year : 2015 - 12 - 31T12 : 07 : 11.980 - get last Day Of Week : 2015 - 01 - 30T12 : 07 : 11.980 |
위 프로그램을 실행하는 데 문제가 있으면 알려주십시오.