-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREADME.md.txt
2284 lines (1666 loc) · 69.1 KB
/
README.md.txt
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### Online markdown editor:
http://markdown.pioul.fr/
### Basic syntax:
https://www.markdownguide.org/basic-syntax/#:~:text=To%20emphasize%20text%20with%20bold,without%20spaces%20around%20the%20letters.
### java 8,9,10,11,12 updates
- java 11: new synchronous HTTP client library
- Lambda: anonymous functions.
- stream: let you manipulate collections of data in a declarative way.
-----------------------------
-----------------------------
-----------------------------
## java 9: Modules and reactive programming toolkit. [synchronization/parallel programming]
- right click on the project
- configure
- create module-info.java
- Packing a Java Module as a Standalone Application
You package a Java module into a standalone application using the jlink command which comes with the Java SDK.
- Here is how you package a Java module with jlink :
```
c:\>jlink
```
- exports com.java.collections.mapList;
-----------------------------
-----------------------------
-----------------------------
## make a copy for a list using streams:
List<Z_Transaction> transactions = new ArrayList<>(Arrays.asList(
new Z_Transaction("a12", 2011, 300),
new Z_Transaction("c14", 2012, 1000),
new Z_Transaction("b13", 2011, 400),
new Z_Transaction("720", 2012, 710),
new Z_Transaction("344", 2012, 700),
new Z_Transaction("983", 2012, 950)
));
// generate new copy
List<Z_Transaction> transactions1 = transactions.stream().collect(Collectors.toList());
List<Z_Transaction> transactions2 = transactions.stream().collect(Collectors.toList());
List<Z_Transaction> transactions3 = transactions.stream().collect(Collectors.toList());
List<Z_Transaction> transactions4 = transactions.stream().collect(Collectors.toList());
List<Z_Transaction> transactions5 = transactions.stream().collect(Collectors.toList());
-----------------------------
-----------------------------
-----------------------------
## Collection Enhancements
## Immutable Collections
### Collection Factories
- List Factory
- Set Factory
- Map Factory
**NEW**
- *List.of()*
- *Set.of()*
- *Map.of()*
- *Map.ofEntries()*
### new ArrayList<>():
```
List<String> friends = new ArrayList<>();
friends.add("Raphael");
friends.add("Olivia");
friends.add("Thibaut");
```
### Arrays.asList("Raphael", "Olivia")
- can update but can NOT add new elements.
- you can change that by using new ArrayList(...) or new HasSet:
_Set<String> friends = new HashSet<>(Arrays.asList("Raphael", "Olivia", Thibaut"));_
```
List<String> friends = Arrays.asList("Raphael", "Olivia");
friends.set(0, "Richard");
friends.add("Thibaut");
```
### Stream.of("Raphael", "Olivia", "Thibaut")..
```
Set<String> friends = Stream.of("Raphael", "Olivia", "Thibaut")
.collect(Collectors.toSet());
```
### __NEW__
- List.of(("Raphael", "Olivia", "Thibaut")
- you still can NOT add elements to it.
- can NOT modify elements.
- does not accept null element.
```
List<String> friends = List.of("Raphael", "Olivia", "Thibaut");
```
- Set.of
- can NOT contain a duplicated element.
- you still can NOT add elements to it.
- can NOT modify elements.
```
Set<String> friends = Set.of("Raphael", "Olivia", "Thibaut");
Set<String> friends = Set.of("Raphael", "Olivia", "Olivia"); <== java.lang.IllegalArgumentException: duplicate element: Olivia
```
- Map.of()
- Map.ofEntries()
- Map.of() create up to 10 key/map fields
- for more element, bigger/more elements use Map.ofEntries()
- will mutate (changes) the same collection
- unlike the stream, it produces a new reult (copy's it).
```
Map<String, Integer> ageOfFriends
= Map.of("Raphael", 30, "Olivia", 25, "Thibaut", 26);
import static java.util.Map.entry;
Map<String, Integer> ageOfFriends
= Map.ofEntries(entry("Raphael", 30),
entry("Olivia", 25),
entry("Thibaut", 26));
```
-----------------------------
-----------------------------
-----------------------------
## Functional Interfaces Summary
---
- Predicate.test() ............. T -> boolean
- Consumer.accept() ............ T -> void
- BiConsumer() ................. (T, U) -> void
- Supplier.get() ............... () -> T
- Function.apply() ............. T -> R
- BinaryOperator ............... (T, T) -> T
---
## Functional Interfaces
you can use lambda expression in the context of a Functional Interface
- contains ONLY one abstract method.
- there is one exception to the rule that only one abstract method is allowed -
- a functional interface can have another abstract methods if they are implemented by java.lang.Object,
- for example toString().
```
(parameters) -> expression
(parameters) -> {statements; } <== Block style lambda
```
- Package java.util.function
### Functions
- T: T stands for "Type"... Object of generic type ***first argument***
- U: type -second argument
- L: ???
- R: Object of generic type return/result
- boolean: true/false
```
- Function Descriptor:
() -> void
(T, T) -> R
```
Function Functional descriptor
-------- ----------------------
Comparator..compare()................... (T, T) -> R.... personList.sort( (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName()) );
Comparator..comparing()................. Comparator<Apple> c = Comparator.comparing(Apple::getWeight());
Comparable..compareTo().................
### Predicate
- .test()............................. T -> boolean... List<String> strString = filter( listOfStrings, (String s) -> s.!s.isEmpty() );
- .isEqual()
- .negate()
```
Predicate<Apple> redApple = (a -> a.getColor().equal(COLOR.RED) );
Predicate<Apple> notRedApple = redApple.negate();
```
- .and()
```
Predicate<Apple> redAndHeavyApple = redApple.and(a->a.getWeight()>150);
```
- .or()
```
Predicate<Apple> redAndHeavyOrGreenApple =
redApple
.and(a->a.getWeight()>150)
.or(a -> a.getColor().equal(COLOR.GREEN))
so, a.or(b).and(c) must be read as: (a || b) && c
a.and(b).or(c) must be read as: (a && b) || c
```
- IntPredicate..test(int i)............... int -> boolean..... IntPredicate evenNumbers = (int i) -> i % 2 == 0;
- DoublePredicate
- BiPredicate............................. (L, R) -> boolean
```
NOTE: Special void-compatibility rule
If a lambda has a statement expression as its body, it’s compatible with a function
descriptor that returns void (provided the parameter list is compatible, too). For
example, both of the following lines are legal even though the method add of a List
returns a boolean and not void as expected in the Consumer context (T -> void):
// Predicate has a boolean return
Predicate<String> p = (String s) -> list.add(s);
// Consumer has a void return
Consumer<String> b = (String s) -> list.add(s);
```
### Consumer.
- .accept()........................... T -> void
```
forEach(Arrays.asList(1,2,3,4,5),(Integer i) -> System.out.println(i) );
```
- IntConsumer
- BiConsumer.......................... (T, U) -> void
### Function.
- zGeneric(T) -> zGeneric(R)
- .apply()....................... T -> R
```
List<Integer> l = zMap(Array.asList( "Lambdas", "in", "action"), (String s) -> s.legth()));
..
public List<Integer> zMap(List<String> list, Function f){
List<Integer> i = ArrayList<>();
for (String s: list){
i.add(f.apply(s));
}
}
```
- .andThen()..................... f.andThen(g) ===> g(f(x))
```
static Function<Integer, Integer> f = x -> x + 1;
static Function<Integer, Integer> g = x -> x * 2;
static Function<Integer, Integer> h = f.andThen(g); // g(f(x))
..
int result = h.apply(1); // 1+1 *2 = 4
```
- .compose()..................... f.compose(g) ===> f(g(x))
```
static Function<Integer, Integer> f = x -> x + 1;
static Function<Integer, Integer> g = x -> x * 2;
static Function<Integer, Integer> m = f.compose(g); // f(g(x))
..
int result = m.apply(1); // 1*2 +1 = 3
```
- IntFunction
- ToIntFunction T -> int
- IntToDoubleFunction
- BiFunction..apply().....................(T, U) -> R....................... (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight())
- ToIntBiFunction<T,T>....................(T,T) -> int
### Supplier.
- .get() () -> T......... () -> new Apple(10) //it takes one argument and returns a result
- BinaryOperator.. (T, T) -> T
- IntBinaryOperator.. (int, int) -> int................. (int a, int b) -> A * b
- LongBinaryOperator
- UnaryOperator.. T -> T
=============================
=============================
=============================
## method reference... _double colon_ '::'
```
http://www.baeldung.com/java-8-double-colon-operator
```
**Bound** *t2*........................ Supplier<String> supplier = t2::method;
**UnBoundc** *lass/instance name*..... Function<Test, String> function = Test::method;
```
EX with [lambda]
inventory.sort( (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()) );
with [method reference]
inventory.sort(Comparator.comparing(Apple::getWeight));
inventory.sort( Comparator.comparing(Apple::getWeight).reversed() );
Composing:
with [.then] if weight the same further comparison needed, ex, by country:
inventory.sort(Comparator.comparing(Apple::getWeight)
.reversed()
.thenComparing(Apple::getCountry)
);
```
Lambda Method reference equivalent
(Apple a) -> a.getWeight() ........................ Apple::getWeight
() -> Thread.currentThread().dumpStack() .......... Thread.currentThread()::dumpStack
(str, i) -> str.substring(i) ...................... String::substring
(String s) -> System.out.println(s) ............... System.out::println
(String s) -> this.isValidName(s).................. this::isValidName
- static method.................................... Integer::parseInt
- instance method.................................. String::length
- local method Transaction expensiveTransaction.... expensiveTransaction::getValue
- constructors reference.. with 0 arguments................... [new Apple()]=========> Supplier<Apple> s = Apple::new; Apple a1 = s.get();
- constructors reference.. with 1 arguments................... [new Apple(weight)]===> Function<Integer, Apple> s = Apple::new; Apple a1 = s.get(110);
- constructors reference.. with 2 arguments................... [new Apple(color, weight)]===> BiFunction<Color, Integer, Apple> s = Apple::new; Apple a1 = s.get(GREEN, 110);
- constructors reference.. with 3 arguments................... create your own CustomTriFunction<T, U, V, R>... see example below
```
EX:
[constructors reference][with 3 arguments]................... create your own CustomTriFunction<T, U, V, R>
public interface CustomTriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}
..
CustomTriFunction<Integer, Integer, Integer, RGB> colorFactory = RGB::new;
EX: expensiveTransaction = new Transaction();
expensiveTransaction::getValue; <====================== () -> expensiveTransaction.getValue();
```
- [array constructors] ???
- [super calls] ???
- https://stackoverflow.com/questions/35914775/java-8-difference-between-method-reference-bound-receiver-and-unbound-receiver
- Java 8: Difference between method reference Bound Receiver and UnBound Receiver
```
EX1
The idea of unBound receiver such as String::length is that you’re referring to a method to
an object that will be supplied as one of the parameters of the lambda.
For example, the lambda expression (String s) -> s.toUpperCase() can be rewritten as String::toUpperCase.
But Bounded refers to a situation when you’re calling a method in a lambda to an external object
that already exists.
For example, the lambda expression () -> expensiveTransaction.getValue()
can be rewritten as expensiveTransaction::getValue.
Situations for three different ways of method reference
basic rules:
(args) -> ClassName.staticMethod(args) can be ClassName::staticMethod
(arg0, rest) -> arg0.instanceMethod(rest) can be ClassName::instanceMethod (arg0 is of type ClassName)
(args) -> expr.instanceMethod(args) can be expr::instanceMethod
Answer retired from Java 8 in Action book
```
```
EX2
Basically, unbound receivers allow you to use instance methods as
if they were static methods with a first parameter of the declaring type - so
you can use them as functions by passing in whatever instance you want.
With a bound receiver, the "target" instance is effectively part of the
function.
An example might make this clearer:
import java.util.function.*;
public class Test {
private final String name;
public Test(String name) {
this.name = name;
}
public static void main(String[] args) {
Test t1 = new Test("t1");
Test t2 = new Test("t2");
Supplier<String> supplier = t2::method;
Function<Test, String> function = Test::method;
// No need to say which instance to call it on -
// the supplier is bound to t2
System.out.println(supplier.get());
// The function is unbound, so you need to specify
// which instance to call it on
System.out.println(function.apply(t1));
System.out.println(function.apply(t2));
}
public String method() {
return name;
}
```
=============================
=============================
=============================
# Streams
## numeric streams [primitive]:
- intStream
- doubleStream
- longStream
- mapToInt
- mapToDouble
- mapToLong
- sum() <==== default 0
- converting from primitive stream to a stream of objects:
```
IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
Stream<Integer> stream = intStream.boxed(); <=== you have to box the IntStream<int> to convert it to a stream<Integer>
```
- OptionalInt
- OptionalDouble
- OptionalLong
- max() <==== default CAN'T be 0
- min()
- average()
- orElse(5) <==== returns primitive value of int '5' [not optional int]
## numeric rage:
- range <================ exclusive (2, 5) '5' is not included: 2,3,4
- rangeClosed <======== inclusive (2, 5) '5' is included: 2,3,4,5
## building streams:
- Stream.of("a", "b", "c")................................... from values
- Stream.empty()............................................. empty stream
- Stream.ofNullable()........................................ from nullable: if no value found, it will create Stream.empty otherwise Stream.of() vlaue
- Arrays.stream(new String[]{"a", "b", "c", "d", "e"})....... from Arrays
- (Arrays.asList("a", "b", "c")).stream()
- Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())...... from files
- Stream.iterate(0, n->n+2).limit(10)........................ from infinite stream
- IntStream.range(1, 100)....................................
- Building streams [summary]:
```
Stream.of()
Stream<String> s = Stream.of("Modern ", "Java ", "In ", "Action");
Stream.empty()
Stream<String> emptyStream = Stream.empty(); // get an empty stream
Stream.ofNullable(
[Java9]
Stream<String> homeValueStream = Stream.ofNullable(System.getProperty("home"));
Arrays.stream()
int sum = Arrays.stream( {2, 3, 5, 7, 11, 13} ).sum();
list2.stream()
[from a List]
List<String> list2 = Arrays.asList("a", "b", "c"); Stream<String> streamL2 = list2.stream();
collc.stream()
[from a Collection]
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> streamOfCollection = collection.stream();
[from a file]
try (Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())) {....}
map.entrySet().stream()
[from a map]
Set<Map.Entry<String, Integer>> entries = someMap.entrySet();
Stream<Map.Entry<String, Integer>> entriesStream = entries.stream();
map.keySet().stream
[from a map..key]
Set<String> keySet = someMap.keySet();
Stream<String> keysStream = keySet.stream();
map.values().stream
[from a map..value]
Collection<Integer> values = someMap.values();
Stream<Integer> valuesStream = values.stream();
Stream.iterate(x,y)
[infinite stream]
Stream.iterate(0, n -> n + 2).limit(10).forEach(System.out::println);
java9
IntStream.iterate(x,y,z)
IntStream.iterate(0, n -> n < 100, n -> n + 4)
//<=== (starting, predicate, lambda function).forEach(System.out::println);
Stream.generate()
[infinite stream]
Stream.generate(() -> Double.toString(Math.random() * 1000)).limit(10);
```
- Stream.concat( Stream(a), Stream(b) ) // also you can use flatMap(): search for an example..
- Stream.of(l1, l2)
- Stream.of(n1, n2).flatMap(Collection::stream);
- Arrays.asList("a", "b", "c");
static List<Dish> specialMenu = Arrays.asList(
new Dish("seasonal fruit", true, 120, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH));
- Stream<String> streamOfWords = Arrays.stream( {"GoodBye", "World"} );
- .stream()
- .parallelStream()
- stream pipeline is similar to the [builder pattern] [chain of calls]
(see http://en.wikipedia.org/wiki/Builder_pattern)
- generating a stream from an ordered collection preserves the ordering.
- Stateless vs stateful
stateless:
.map
.filter
..
stateful:
.reduce [bounded]
.sorted [unbounded]
.distict [unbounded]
.skip [bounded]
.limit [bounded]
..
-intermediate and terminal operations
-[lazy] intermediate operations: <====== return another stream
xyz.stream()
.filter [T -> boolean]
.sorted [(T, T) -> int]
.distinct [lazy]???
.map() [short-circuiting] [T -> R] <==== function to create a new version of... [NOT modifying]
.map() <======================= you can use multiple map(s), filter(s) ..
.mapToInt()
.mapToLong()
.mapToDouble()
.flatmap <====================== combine multiple maps into one Stream<string[]>'s to Stream<String>
.flatMapToInt
.flatMapToLong
.flatMapToDouble
.concat(Stream<? extends T> a, Stream<? extends T> b)()
.limit()
.skip() <======================= discards the first (n) elements.
.build()
.sorted
[Java9]
.takeWhile <==================== [must be a sorted list] +stops once an element found >= 320
.dropWhile <==================== [must be a sorted list] +stops once an element found > 320
-terminal operations: <=============== result in any non-stream value [ex: list, Integer, void...]
import static java.util.stream.Collectors.*;
.collect
(Collectors.toList()
(Collectors.toSet()
(Collectors.counting()
(Collectors.maxBy(Comparator<T>)
(Collectors.minBy(Comparator<T>)
(Collectors.summingInt()
(Collectors.joining(",")
(Collectors.reducing(x,y,z)
(Collectors.groupingBy(Person::getCity)
(Collectors.groupingBy(..lambda..)
(Collectors.groupingBy(Dish::getType,
Collectors.filtering(dish -> dish.getCalories() > 500, Collectors.toList())
));
(Collectors.groupingBy(Dish::getType,
Collectors .flatMapping(dish -> dishTags.get( dish.getName() ) .stream(), Collectors.toSet())));
.forEach
.count
.allMatch
.anyMatch
.noneMatch
.reduce <======================= a stream is reduced to a value
.findFirst()
.findAny()
.findEach()
------------------------------
------------------------------
[.distinct]
// you can use it to remove duplicates
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
numbers.stream()
.filter(i -> i % 2 == 0)
.distinct()
.forEach(System.out::println);
slicing
[.takeWhile]
// [already sorted elements] use to stop (selecting) filtering when it is true
import static java.util.stream.Collectors.*;
List<Dish> filteredMenu = specialMenu
.stream()
.takeWhile(dish -> dish.getCalories() < 320) // [must be a sorted list] +stops once a dish found >= 320
.collect(toList());
slicing
[.dropWhile]
// [already sorted elements] use to select filtering when the ones that's not true [the opposite of .takeWhile]
import static java.util.stream.Collectors.*;
List<Dish> filteredMenu = specialMenu
.stream()
.dropWhile(dish -> dish.getCalories() < 320) // [must be a sorted list] +starts selecting once a dish found >= 320
.collect(toList());
[filter]
[limit]
import static java.util.stream.Collectors.*;
List<Dish> dishes = menu
.stream()
.filter(dish -> dish.getType() == Dish.Type.MEAT)
.limit(2)
.collect(toList());
[filter]
[skip]
// map is almost like select a particular column in sql
[map]
[mapToInt]
[mapToDouble]
[mapToLong]
.map(Transaction::getValue);
..
int calories = menu.stream()
.mapToInt(Dish::getCalories)
.sum();
..
Numeric Stream:
[OptionalInt]
[OptionalDouble]
[OptionalLong]
.get()
.orElse()
.orElseGet()
OptionalInt maxCalories = menu.stream()
.mapToInt(Dish::getCalories)
.max();
int max = maxCalories.orElse(1); <============================= // if no elements, set default value to 1
Numeric Stream:
[IntStream]
[DoubleStream]
[LongStream]
-supports: .sum .min .max .average .rang .rangClosed
IntStream intStream = IntStream.range(1, 100); // exclusive [1-99] [100 not included]
IntStream intStream = IntStream.rangeClosed(1, 100) // inclusive [1-100][100 is included]
.filter(n -> n%2 == 0);
// converting back to a stream of Objects [int -> Integer]
IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
Stream<Integer> stream = intStream.boxed(); <=== you have to box the IntStream<int> to convert it to a stream<Integer>
[flatmap]
[flatMapToInt]
Stream can hold different data types, But, the Stream operations (filter, sum, distinct…) and collectors do not support it,
so, we need flatMap() to do the following conversion :
Stream<String[]> -> flatMap -> Stream<String>
Stream<Set<String>> -> flatMap -> Stream<String>
Stream<List<String>> -> flatMap -> Stream<String>
Stream<List<Object>> -> flatMap -> Stream<Object>
How flatMap() works :
{ {1,2}, {3,4}, {5,6} } -> flatMap -> {1,2,3,4,5,6}
{ {'a','b'}, {'c','d'}, {'e','f'} } -> flatMap -> {'a','b','c','d','e','f'}
EX:
import static java.util.stream.Collectors.*;
List<String> words = Arrays.asList("Goodbye", "World");
List<String> uniqueCharacters = words
.stream()
.map(word -> word.split("")) // convert each word into an array of its individual letters
// each word => String[] of letters
.flatMap(Arrays::stream) // flatten each generated stream into a single stream
.distinct()
.collect(toList());
EX:
// combine two lists.
// first combine two lists into a stream [using flatMap] and then collecting it into a list [Collectors.toList()].
Stream<String> combinedStream = Stream.of(collectionA, collectionB)
.flatMap(Collection::stream);
Collection<String> collectionCombined =
combinedStream.collect(Collectors.toList());
EX: // Stream<List<String>> -> flatMap -> Stream<String>
import static java.util.stream.Collectors.*;
public class Student {
private String name;
private Set<String> book;
public void addBook(String book) {
if (this.book == null) {
this.book = new HashSet<>();
}
this.book.add(book);
}
//getters and setters
// getBook()
}
--- main()
Student obj1 = new Student();
obj1.setName("mkyong");
obj1.addBook("Java 8 in Action");
obj1.addBook("Spring Boot in Action");
obj1.addBook("Effective Java (2nd Edition)");
Student obj2 = new Student();
obj2.setName("zilap");
obj2.addBook("Learning Python, 5th Edition");
obj2.addBook("Effective Java (2nd Edition)");
List<Student> list = new ArrayList<>();
list.add(obj1);
list.add(obj2);
//import static java.util.stream.Collectors.*;
List<String> collect =
list.stream()
.map(x -> x.getBook()) //Stream<Set<String>>
.flatMap(x -> x.stream()) //Stream<String>
.distinct()
.collect(Collectors.toList());
collect.forEach(x -> System.out.println(x));
EX:
int[] intArray = {1, 2, 3, 4, 5, 6};
//1. Stream<int[]>
Stream<int[]> streamArray = Stream.of(intArray);
//2. Stream<int[]> -> flatMap -> IntStream
IntStream intStream = streamArray.flatMapToInt(x -> Arrays.stream(x));
intStream.forEach(x -> System.out.println(x));
EX:
List<String> betterLetters = Stream.of(l1, l2)
.flatMap(List::stream)
.map(String::toUpperCase)
.collect(Collectors.toList());
[concat]
// combine two lists
Stream<String> combinedStream = Stream.concat(
collectionA.stream(),
collectionB.stream()
);
// combine multiple lists
Stream<String> combinedStream = Stream.concat(
Stream.concat(collectionA.stream(), collectionB.stream()),
collectionC.stream()
);
[anyMatch]..
[allMatch]..
[nonMatch].. returns boolean
if(menu.stream().anyMatch(Dish::isVegetarian)) {
System.out.println("The menu is (somewhat) vegetarian friendly!!");
}
..
boolean isHealthy = menu.stream()
.allMatch(dish -> dish.getCalories() < 1000);
..
boolean isHealthy = menu.stream()
.noneMatch(d -> d.getCalories() >= 1000);
[findAny]... returns Optional
Optional<Dish> dish =
menu.stream()
.filter(Dish::isVegetarian)
.findAny();
OR
menu.stream()
.filter(Dish::isVegetarian)
.findAny() //<======================================== returns Optional<Dish>
.ifPresent(dish -> System.out.println(dish.getName());
[findFirst]
// for example, the code that follows, given a list of numbers,
// finds the first square that’s divisible by 3):
// Returns an Optional<Dish>. If a value is contained,
// it’s printed; otherwise
// nothing happens.
List<Integer> someNumbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstSquareDivisibleByThree =
someNumbers.stream()
.map(n -> n * n)
.filter(n -> n % 3
[reduce]
[Integer::sum]
[Integer::max]
[Integer::min]
// a stream is reduced to a value
EX: sum all elements and preduce a new value
0: is the initial value
(a, b) -> a + b : BinaryOperator<T> to combine two elements
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
{4,5,3,9}==21
OR
int sum = numbers.stream().reduce(0, Integer::sum);
OR
// NO INITIAL VALUE, will return Optional<Integer>
Optional<Integer> sum = numbers.stream().reduce((a, b) -> (a + b));
..
EX: multiply all elements
int product = numbers.stream().reduce(1, (a, b) -> a * b);
.
Optional<Integer> max = numbers.stream().reduce(Integer::max);
..
Optional<Integer> min = numbers.stream().reduce(Integer::min);
OR
Optional<Integer> min = numbers.stream().reduce((x, y) -> x < y ? x : y);
..
[sorted]
transactions.stream()
.filter(t -> t.getYear() == 2011)
.map(Transaction::getValue)
.sorted()
//.sorted(Comparator.reverseOrder())
.forEach(System.out::println);
## Collection
## collect
## Collectors
- group a list
- partition a list
- grouping and sub-grouping
### collect()
import static java.util.stream.Collectors.*;
- Collectors.toList()
List<Transaction> transactions = transactionStream
.collect(Collectors.toList());
- Collectors.counting()]
long howManyDishes = menu.stream().collect(Collectors.counting()); // menu.stream().count();
[Collectors.maxBy()]
[Collectors.minBy()]
Comparator<Dish> dishCaloriesComparator = Comparator.comparingInt(Dish::getCalories);
Optional<Dish> mostCalorieDish = menu.stream()
.collect(maxBy(dishCaloriesComparator));
[Collectors.summingInt()]
[Collectors.summingDouble()]
[collecters.averagingInt()]
[collecters.averagingLong()]
[collecters.averagingDouble()]
[collecters.summarizingInt()]
int totalCalories = menu.stream().collect(summingInt(Dish::getCalories));
double totalCalories = menu.stream().collect(summingDouble(Dish::getCalories));
double avgCalories = menu.stream().collect(averagingInt(Dish::getCalories));
IntSummaryStatistics menuStatistics = menu.stream().collect(summarizingInt(Dish::getCalories));
LongSummaryStatistics..
DoubleSummaryStatistics..
[collecters.joining()] ... default 'space'
[collecters.joining(", ")]
String shortMenu = menu.stream().map(Dish::getName).collect(joining());
String shortMenu2 = menu.stream().map(Dish::getName).collect(joining(", "));
NOTE:
if Dish has toString() method that returns the dish name, both produce a string value:
String shortMenu = menu.stream().collect(joining());
[collecters.reducing(x,y,z)]
int totalCalories0 = menu.stream().collect(
reducing(0, //....................... initial value
Dish::getCalories, //....................... transformation function
Integer::sum)); //....................... aggregating function
int totalCalories2 = menu.stream().collect(reducing( 0, Dish::getCalories, (i, j) -> i + j) );
Optional<Dish> mostCalorieDish2 = menu.stream().collect(reducing( (d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2) );
NOTE: groupingBy(f) ==> shorthand for groupingBy(f, toList())
NOTE: groupingBy generates a Map<x, list<>)
OR
groupingBy(Map<x, Map<y, list<>>) <=== inner groupingBy
NOTE: groupingBy( k.., v[filtering.., output..] )
NOTE: groupingBy( k.., v[mapping.., output..] )
[counting()
[maxBy()
[(Collectors.groupingBy()]
[groupingByConcurrent()] same as above
[Map] [:: method reference]