1
+ package com .howtodoinjava .core .streams ;
2
+
3
+ import java .util .List ;
4
+ import java .util .stream .Collectors ;
5
+
6
+ public class MapMultiExample {
7
+
8
+ public static void main (String [] args ) {
9
+
10
+ List <Integer > numbers = List .of (1 , 2 , 3 );
11
+
12
+ List <Integer > multiples = numbers .stream ().<Integer >mapMulti ((num , downstream ) -> {
13
+ downstream .accept (num );
14
+ downstream .accept (num * num ); // Add the square of the number
15
+ downstream .accept (num * num * num ); // Add the cube of the number
16
+ }).toList ();
17
+
18
+ System .out .println (multiples ); // Output: [2, 3, 4, 6, 6, 9, 8, 12, 10, 15]
19
+
20
+ // second example
21
+
22
+ // Sample list of transactions
23
+ List <Transaction > transactions = List .of (
24
+ new Transaction ("T1" , 100 , TransactionType .DEPOSIT ),
25
+ new Transaction ("T2" , 50 , TransactionType .WITHDRAWAL ),
26
+ new Transaction ("T3" , 200 , TransactionType .WITHDRAWAL ));
27
+
28
+ // Process transactions and generate transaction events
29
+ List <TransactionEvent > transactionEvents = transactions .stream ()
30
+ .<TransactionEvent >mapMulti ((transaction , downstream ) -> {
31
+ if (transaction .getType () == TransactionType .DEPOSIT ) {
32
+ downstream .accept (new TransactionEvent ("Deposit" , transaction .getAmount ()));
33
+ } else if (transaction .getType () == TransactionType .WITHDRAWAL ) {
34
+ downstream .accept (new TransactionEvent ("Withdrawal" , transaction .getAmount ()));
35
+ // If withdrawal amount is greater than 100, generate an additional fraud alert event
36
+ if (transaction .getAmount () > 100 ) {
37
+ downstream .accept (new TransactionEvent ("Fraud Alert" , transaction .getAmount ()));
38
+ }
39
+ }
40
+ }).toList ();
41
+
42
+ // Print the generated transaction events
43
+ transactionEvents .forEach (System .out ::println );
44
+ }
45
+
46
+ static class Transaction {
47
+
48
+ private String id ;
49
+ private double amount ;
50
+ private TransactionType type ;
51
+
52
+ public Transaction (String id , double amount , TransactionType type ) {
53
+ this .id = id ;
54
+ this .amount = amount ;
55
+ this .type = type ;
56
+ }
57
+
58
+ public String getId () {
59
+ return id ;
60
+ }
61
+
62
+ public double getAmount () {
63
+ return amount ;
64
+ }
65
+
66
+ public TransactionType getType () {
67
+ return type ;
68
+ }
69
+ }
70
+
71
+ static class TransactionEvent {
72
+
73
+ private String type ;
74
+ private double amount ;
75
+
76
+ public TransactionEvent (String type , double amount ) {
77
+ this .type = type ;
78
+ this .amount = amount ;
79
+ }
80
+
81
+ @ Override
82
+ public String toString () {
83
+ return "TransactionEvent{" + "type='" + type + '\'' + ", amount=" + amount + '}' ;
84
+ }
85
+ }
86
+
87
+ enum TransactionType {
88
+ DEPOSIT , WITHDRAWAL
89
+ }
90
+ }
0 commit comments