Java 8 java.temps.temporel. Tutoriel TemporalAdjusters et Stream.flatMap()
Publié: 2020-09-09
Cela fait presque 2 ans que Java 8 est sorti, en mars 2014. Je suis sûr que la plupart des entreprises utilisent encore Java 7 avec Apache Tomcat dans leur environnement de production, mais récemment, il prend de l'ampleur.
Comme la plupart des entreprises utilisent encore Java 7, il existe de nombreuses fonctionnalités inaperçues dans le monde.
Il y a quelque temps, nous avons écrit un article détaillé sur l'API Java 8 Stream et Lambda Expression. Dans ce tutoriel, nous allons passer en revue l'exemple java.time.temporal.TemporalAdjusters
et flatMap()
.
ObjetsTemporels
Que sont les tempoalObjects
en Java ? Il s'agit d'une interface au niveau du framework traitant des objets de date et d'heure, principalement read-only objects
qui fournissent un accès de generic manner
.
Ajusteurs Temporels
Les TemporalAdjusters sont un outil clé pour modifier les objets temporels. Il existe deux manières d'utiliser TemporalAdjuster.
- Invoquez la méthode directement sur l'interface
- utiliser Temporal.with(TemporalAdjuster)

Stream.flatMap()
Java map
et flatMap
peuvent être appliqués à un Stream<T>
et ils renvoient tous les deux un Stream<R>
. Quelle est la différence ?
- l'opération de
map
produit une valeur de sortie pour chaque valeur d'entrée - L'opération
flatMap
produit un nombre arbitraire (zéro ou plus) de valeurs pour chaque valeur d'entrée
Commençons par le didacticiel
- Créer la classe CrunchifyJava8TemporalAdjustersAndFlatMap.java
- Nous allons créer deux méthodes simples
- crunchifyStreamFlatMapExample
- crunchifyTemporalExemple
- Tous les détails sont fournis dans chaque méthode elle-même en tant que commentaire
- Exécutez le programme et vérifiez le résultat
- assurez-vous d'avoir configuré JDK 8 dans l'environnement Eclipse
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 ) ) ) ; } } |
Sortir:
Voici un résultat console. Exécutez simplement le programme Java ci-dessus et vous verrez le résultat comme ci-dessous.

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 |
Faites-nous savoir si vous rencontrez un problème lors de l'exécution du programme ci-dessus.