Java 8 Stream & C# 3.5
Trần Duy Quang – May 2014
Agenda
1. Some notable new things in Java 8
2. Comparison with LINQ in C# 3.5!
2
1
Some new things in Java 8
Notable things
Lambda expressions
Default methods
Method reference
Stream
Optional
New Date & Time API
Functional programming
Reference (blog post): Everything about Java 84
Lambda expression
5
(x, y) -> x + y
Passing function around
Dynamically (usually weakly) typed: Javascript
Strongly typed: Ruby, Scala, Closure
6
Functional approach
Concise UsefulParalellizable
Why lambda in Java now?
Clearer than anonymous inner class
Basic for stream library
shapes.forEach(s -> s.setColor(Color.RED));
A step toward functional programming !
7
Main advantage of lambdas
Concise & expressive
8
New way of thinking
Encourage functional programming
Many classes of problems are easier to solve
Code is clearer to read, simpler to maintain
9
What we actually get?
An instance of a class that implements the
interface that was expected in that place
Remember this?
Interface that has exactly one abstract method!
Functional Interface | Single Abstract Method
10
Shortening lambda syntax
Omit parameter types
Expressions instead of blocks
Single arguments? Omit parenthesis!
11
Even better with high-order function
High-order function: method return lambdas
comparing method of Comparator need function
specifying how to extract the key
12
Method reference
13
Core idea behind
Make lambda more succinct!
Rather than
angles.map(x -> Math.sin(x));
Can be shorthand
angles.map(Math::sin);
14
Predicate
15
Core idea behind
Boolean test(T t)
A function to test condition
16
Benefit: Flexibility
Even better with stream (later slides)
17
Similar things
Predicate: boolean test(T t)
Check a condition
Consumer: void consume(T t)
Perform action with the given object
BiConsumer: with two parameters
Function: R change(T t)
Take an object type T and return new object type R
BiFunction: with two parameters
Supplier: T supply(T t)
Return an object with the same type
18
More convenient helper classes
IntConsumer
IntFunction<R>
IntPredicate
IntSupplier
19
Stream
20
Stream
Wrapper around data sources: arrays, collections…
Use lambdas
Support map/reduce
Lazy evaluation
Made parallel atutomatically by compiler
21
Making streams
From individual values Stream.of(val1, val2,…)
From array Stream.of(names), Arrays.stream(names)
From List (and other collections) names.stream()
From a StreamBuilder builder.build()
From String String.chars, Arrays.stream(s.split())
From another stream distinct, filter, map, limit, sorted, substream
22
Turn stream to other data structures
Array
employees.toArray(Employee[]::new);
List
names.collect(Collectors.toList());
Set
names.collect(Collectors.toSet());
23
2
Comparison with LINQ in C#
Restriction Operators
25
1. Filtering
Find names where “am” occurs
26
2. Indexed Filtering (tricky)
Find names where length <= index + 1
(generate an indexed stream out of the original array)
27
Projection Operators
28
3. Selecting/Mapping
Add “Hello “ in front of each names
29
4. Selecting Many/Flattening
Project all the elements in a single collection
Java: Transform to entry set, then flatten
30
Partitioning Operators
31
5. Taking an Arbitrary Number of Items
Obtain the first 4 items
Java: convert IntStream into Stream<Integer>
32
6. Taking Items Based on Predicate
Take while having the string that start with “S”
Java: don’t have the short-circuited ability, have to
create Boolean map
33Different meaning from the above!
7. Skipping an Arbitrary Number of Items
Skip top items, take the rest
Java:
34
8. Skipping Items Based on Predicate
LINQ: SkipWhile
Sadly, no way in Java
35
Ordering Operators
36
9. Ordering/Sorting Elements
Order the elements of a collection alphabetically
Java:
37
10. Ordering/Sorting Elements by
Specific Criterium
Ordering by the length of the string
Java
Shorthand:
38
11. Ordering/Sorting Elements by
Multiple Criteria
Sort by length, then by order
Java:
39
Grouping Operators
40
12.Grouping by a Criterium
Group collection of strings by their length
41
Set Operators
42
13. Filter Distinct Elements
Obtain all the distinct elements from a collection
43
14. Union of Two Sets
Join together two sets of items
44
Element Operatos
45
15. First Element
Obtain the first element of a collection
Java: Maybe better!
46
Range Operators
47
16. Generate a Range of Numbers
Generate a range of no that are multiples of 11
48
Quantifier Operators
49
17. All
Do all elements in a collection satisfy a predicate?
50
18. Any
Do any elements in a collection satisfy a predicate?
51
Merging Operators
52
19.Zip
Combine two collections into a single collection
53
The last coffee drop
54
Still left behind by C#! Gambatte, Java!
Make IntelliJ IDEA work with Java 8
Make sure you have the latest version (>=13.1.2)
Change project language level to 8.0 (F4)
56
Reference
Blog post: Java Streams Preview vs .Net High-
Order Programming with LINQ
Slide: Evolution of Java
Slide: Lambda expressions & Stream in Java 8
Slide: Java 8 Stream Tutorial Part 1
Slide: Java 8 Stream Tutorial part 2
Just for fun (Youtube Video 20”):
Javapocalypse ^^
57