SlideShare a Scribd company logo
Scala Collections : Java 8 on Steroids
François Garillot
Twitter : @huitseeker
francois.garillot@typesafe.com
1
What this talk is
2
What this talk is
A look at Java 8 gives you
2-a
What this talk is
A look at Java 8 gives you
... and what it doesn’t
2-b
What this talk is
A look at Java 8 gives you
... and what it doesn’t
A look at Scala collections
2-c
What this talk is
A look at Java 8 gives you
... and what it doesn’t
A look at Scala collections
A look at the why and how of collections
2-d
What this talk is not
3
What this talk is not
New stuff
3-a
What this talk is not
New stuff
Rocket Science
3-b
What this talk is not
New stuff
Rocket Science
Polemic
3-c
What I’m hoping for
4
What I’m hoping for
A discussion
4-a
What I’m hoping for
A discussion
Making things a tad more clear
4-b
What I’m hoping for
A discussion
Making things a tad more clear
... or just less overlooked ?
4-c
What I’m hoping for
A discussion
Making things a tad more clear
... or just less overlooked ?
Not too boring
4-d
What (functional, new things) you can do with Java 8
Lambda-expressions
(String first, String second) ->
Integer.compare(first.length(), second.length)
Functional Interfaces
Runnable r = () -> System.out.println("I am Runnable!");
Method references
button.setOnAction(System.out::println);
Constructor references
List<String> labels = ... ;
Stream<Button> buttonsStream = labels.stream().map(Button::new);
Buttons[] buttonsArray = labels.stream().toArray(Button::new);
int[]::new;
5
The devil is in the details
Optional<T>, Optional.of(), Optional.ofNullable(), Optional.empty()
Default methods in interfaces.
list.forEach(System.out::println)
... beware: SuperClasses win, Interfaces clash. ... And the standard library was not
entirely rewritten (Path/Paths)
Important topics : variable capture in closures, parallel execution.
int[] counter = new int[1];
button.setOnAction(event -> counter[0]++);
6
And also, Streams
Any Collection has a stream()
Stream.of() with a vararg, an array
filter, map, flatMap, as well as plumbing: split, concat, limit
Lazy processing, parallel() processing (you enforce statelessness)
terminal reductions, e.g. reduce
collector:
HashSet<String> result =
stream.collect(HashSet::new, HashSet::add, HashSet::addAll)
Collector implementations (toList, toMap, ...)
counting, maxBy, groupinBy, mapping, ...
Beware: think about reuse.
7
Interlude
8
Interlude
Does that make Java a functional programming language ?
8-a
Interlude
Does that make Java a functional programming language ?
First class functions
8-b
Interlude
Does that make Java a functional programming language ?
First class functions
Technicalities
8-c
Interlude
Does that make Java a functional programming language ?
First class functions
Technicalities
Does that make Java a Scala competitor ?
8-d
Interlude
Does that make Java a functional programming language ?
First class functions
Technicalities
Does that make Java a Scala competitor ?
Scala has never had a feature poverty problem.
8-e
What you can’t do with Java 8 (yet)
1. Case classes
2. Pattern matching
3. Tail call elimination
4. Scoped access
5. Lazy keyword
6. Traits (well-scoped)
7. Rich Imports (local, aliased)
8. Macros
9. Backend (Miguel Garcia)
10. Specialization (Vlad Ureche)
11. Value classes
12. Implicits
13. Cake !
9
Collections
The signatures of map
Type classes & implicits
Design goals
10
The signatures of map
11
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
11-a
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
But ... Type Constructor Polymorphism
11-b
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
But ... Type Constructor Polymorphism
trait TraversableLike[+Elem, +Coll[+x]] {
def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem]
def filter(p: Elem ⇒ Boolean): Coll[Elem]
}
11-c
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
But ... Type Constructor Polymorphism
trait TraversableLike[+Elem, +Coll[+x]] {
def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem]
def filter(p: Elem ⇒ Boolean): Coll[Elem]
}
The idea that, whatever map needs, it will always deal with:
11-d
The signatures of map
def map[B](f: (A) ⇒ B) : Map[B]
But ... Type Constructor Polymorphism
trait TraversableLike[+Elem, +Coll[+x]] {
def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem]
def filter(p: Elem ⇒ Boolean): Coll[Elem]
}
The idea that, whatever map needs, it will always deal with:
(Collection[Elements],
Elements ⇒ OtherElements,
Collection[OtherElements])
11-e
The signatures of map
12
The signatures of map
12-a
The signatures of map
trait TraversableLike[+Elem, +Repr] {
protected[this] def newBuilder: Builder[Elem, Repr] // deferred
def foreach[U](f: Elem ⇒ U) // deferred
def filter(p: Elem ⇒ Boolean): Repr = {
val b = newBuilder
foreach { elem <- if (p(elem)) b += elem }
b.result
}
}
class Builder[-Elem, +To] {
def +=(elem: Elem): this.type = . . .
def result(): To = . . .
def clear() = . . .
def mapResult[NewTo](f: To ⇒ NewTo): Builder[Elem, NewTo] = . . .
}
12-b
The signatures of map
trait TraversableLike[+Elem, +Repr] {
protected[this] def newBuilder: Builder[Elem, Repr] // deferred
def foreach[U](f: Elem ⇒ U) // deferred
def filter(p: Elem ⇒ Boolean): Repr = {
val b = newBuilder
foreach { elem <- if (p(elem)) b += elem }
b.result
}
}
class Builder[-Elem, +To] {
def +=(elem: Elem): this.type = . . .
def result(): To = . . .
def clear() = . . .
def mapResult[NewTo](f: To ⇒ NewTo): Builder[Elem, NewTo] = . . .
}
Why do we care ? Extensibility.
12-c
The signatures of map (cont’d)
13
The signatures of map (cont’d)
13-a
The signatures of map (cont’d)
def map[B, That](f: ((A,B)) ⇒ B)
(implicit bf:CanBuildFrom[Map[A,B], B, That]):That
13-b
The signatures of map (cont’d)
def map[B, That](f: ((A,B)) ⇒ B)
(implicit bf:CanBuildFrom[Map[A,B], B, That]):That
Why ?
13-c
The signatures of map (cont’d)
def map[B, That](f: ((A,B)) ⇒ B)
(implicit bf:CanBuildFrom[Map[A,B], B, That]):That
Why ?
Dealing with (Bitset, Int, BitSet) and
(Bitset, String, Set[String])
13-d
The signatures of map (cont’d)
def map[B, That](f: ((A,B)) ⇒ B)
(implicit bf:CanBuildFrom[Map[A,B], B, That]):That
Why ?
Dealing with (Bitset, Int, BitSet) and
(Bitset, String, Set[String])
Dealing with (Map[A, B], (A, B)) ⇒ (B, A), Map[B, A]) and
(Map[A, B], (A, B)) ⇒ T, Iterable[T])
13-e
With Implicits
trait CanBuildFrom[-Collection, -NewElem, +Result] {
def apply(from: Collection): Builder[NewElem, Result]
}
trait TraversableLike[+A, +Repr] {
def repr: Repr = . . .
def foreach[U](f: A ⇒ U): Unit = . . .
def map[B, To](f: A ⇒ B)(implicit cbf: CanBuildFrom[Repr, B, To]): To = {
val b = cbf(repr) // get the builder from the CanBuildFrom instance
for (x <- this) b += f(x) // transform element and add
b.result
}
}
14
trait SetLike[+A, +Repr] extends TraversableLike[A, Repr] { }
trait BitSetLike[+This <: BitSetLike[This] with Set[Int]]
extends SetLike[Int, This] {}
trait Traversable[+A] extends TraversableLike[A, Traversable[A]]
trait Set[+A] extends Traversable[A] with SetLike[A, Set[A]]
class BitSet extends Set[Int] with BitSetLike[BitSet]
object Set {
implicit def canBuildFromSet[B] = new CanBuildFrom[Set[_], B, Set[B]] {
def apply(from: Set[_]) = . . .
}
}
object BitSet {
implicit val canBuildFromBitSet = new CanBuildFrom[BitSet, Int, BitSet] {
def apply(from: BitSet) = . . .
}
}
15
Conclusion
A word about design.
16

More Related Content

PPT
Collections Framework
PDF
Java Collections API
PDF
Collections In Java
PDF
Collections in Java Notes
PDF
Java Collections Tutorials
PPT
Java collection
PPTX
Java - Collections framework
Collections Framework
Java Collections API
Collections In Java
Collections in Java Notes
Java Collections Tutorials
Java collection
Java - Collections framework

What's hot (19)

PPSX
Collections - Lists, Sets
PPT
java collections
PDF
Java Collection framework
PPT
Collections in Java
PPSX
Collections - Maps
DOCX
Java collections notes
PDF
Collections Java e Google Collections
PPT
Java Collections Framework
PPSX
Collections - Array List
PDF
5 collection framework
PPTX
Java collections
PDF
07 java collection
PPTX
Lecture11 standard template-library
PDF
Collections Api - Java
PPTX
Collections - Lists & sets
PPT
Java collections concept
ODP
Java Collections
PPT
Collection Framework in java
Collections - Lists, Sets
java collections
Java Collection framework
Collections in Java
Collections - Maps
Java collections notes
Collections Java e Google Collections
Java Collections Framework
Collections - Array List
5 collection framework
Java collections
07 java collection
Lecture11 standard template-library
Collections Api - Java
Collections - Lists & sets
Java collections concept
Java Collections
Collection Framework in java
Ad

Similar to Scala Collections : Java 8 on Steroids (20)

PDF
Big picture of category theory in scala with deep dive into contravariant and...
PDF
Big picture of category theory in scala with deep dive into contravariant and...
PPTX
Taking your side effects aside
PDF
Scheme on WebAssembly: It is happening!
PDF
Talk - Query monad
PDF
Scala.io
PDF
Generic Functional Programming with Type Classes
PDF
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
PDF
JSDC 2014 - functional java script, why or why not
PDF
Contravariant functors in scala
PDF
Coding in Style
PDF
A Few of My Favorite (Python) Things
PDF
Refactoring to Macros with Clojure
PDF
Functor, Apply, Applicative And Monad
PPTX
Running Free with the Monads
PDF
Building a Functional Stream in Scala
PPTX
Developing High Performance Application with Aerospike & Go
PDF
Kyo - Functional Scala 2023.pdf
PDF
famous placement papers
PDF
Chapter 1
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
Taking your side effects aside
Scheme on WebAssembly: It is happening!
Talk - Query monad
Scala.io
Generic Functional Programming with Type Classes
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
JSDC 2014 - functional java script, why or why not
Contravariant functors in scala
Coding in Style
A Few of My Favorite (Python) Things
Refactoring to Macros with Clojure
Functor, Apply, Applicative And Monad
Running Free with the Monads
Building a Functional Stream in Scala
Developing High Performance Application with Aerospike & Go
Kyo - Functional Scala 2023.pdf
famous placement papers
Chapter 1
Ad

More from François Garillot (9)

PDF
Modern multi-proposer consensus implementations
PDF
Growing Your Types Without Growing Your Workload
PDF
Deep learning on a mixed cluster with deeplearning4j and spark
PDF
Mobility insights at Swisscom - Understanding collective mobility in Switzerland
PDF
Delivering near real time mobility insights at swisscom
PDF
Spark Streaming : Dealing with State
PDF
A Gentle Introduction to Locality Sensitive Hashing with Apache Spark
PDF
Ramping up your Devops Fu for Big Data developers
PDF
Diving In The Deep End Of The Big Data Pool
Modern multi-proposer consensus implementations
Growing Your Types Without Growing Your Workload
Deep learning on a mixed cluster with deeplearning4j and spark
Mobility insights at Swisscom - Understanding collective mobility in Switzerland
Delivering near real time mobility insights at swisscom
Spark Streaming : Dealing with State
A Gentle Introduction to Locality Sensitive Hashing with Apache Spark
Ramping up your Devops Fu for Big Data developers
Diving In The Deep End Of The Big Data Pool

Recently uploaded (20)

PPTX
Application of enzymes in medicine (2).pptx
PDF
An interstellar mission to test astrophysical black holes
PDF
Lymphatic System MCQs & Practice Quiz – Functions, Organs, Nodes, Ducts
PDF
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
PPTX
Overview of calcium in human muscles.pptx
PDF
lecture 2026 of Sjogren's syndrome l .pdf
DOCX
Q1_LE_Mathematics 8_Lesson 5_Week 5.docx
PDF
Placing the Near-Earth Object Impact Probability in Context
PDF
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
PDF
Mastering Bioreactors and Media Sterilization: A Complete Guide to Sterile Fe...
PPT
protein biochemistry.ppt for university classes
PPT
POSITIONING IN OPERATION THEATRE ROOM.ppt
PPTX
BIOMOLECULES PPT........................
PPTX
Pharmacology of Autonomic nervous system
PPTX
neck nodes and dissection types and lymph nodes levels
PPTX
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
PPTX
Taita Taveta Laboratory Technician Workshop Presentation.pptx
PPTX
Introduction to Fisheries Biotechnology_Lesson 1.pptx
PDF
Cosmic Outliers: Low-spin Halos Explain the Abundance, Compactness, and Redsh...
PPTX
famous lake in india and its disturibution and importance
Application of enzymes in medicine (2).pptx
An interstellar mission to test astrophysical black holes
Lymphatic System MCQs & Practice Quiz – Functions, Organs, Nodes, Ducts
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
Overview of calcium in human muscles.pptx
lecture 2026 of Sjogren's syndrome l .pdf
Q1_LE_Mathematics 8_Lesson 5_Week 5.docx
Placing the Near-Earth Object Impact Probability in Context
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
Mastering Bioreactors and Media Sterilization: A Complete Guide to Sterile Fe...
protein biochemistry.ppt for university classes
POSITIONING IN OPERATION THEATRE ROOM.ppt
BIOMOLECULES PPT........................
Pharmacology of Autonomic nervous system
neck nodes and dissection types and lymph nodes levels
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
Taita Taveta Laboratory Technician Workshop Presentation.pptx
Introduction to Fisheries Biotechnology_Lesson 1.pptx
Cosmic Outliers: Low-spin Halos Explain the Abundance, Compactness, and Redsh...
famous lake in india and its disturibution and importance

Scala Collections : Java 8 on Steroids

  • 1. Scala Collections : Java 8 on Steroids François Garillot Twitter : @huitseeker [email protected] 1
  • 3. What this talk is A look at Java 8 gives you 2-a
  • 4. What this talk is A look at Java 8 gives you ... and what it doesn’t 2-b
  • 5. What this talk is A look at Java 8 gives you ... and what it doesn’t A look at Scala collections 2-c
  • 6. What this talk is A look at Java 8 gives you ... and what it doesn’t A look at Scala collections A look at the why and how of collections 2-d
  • 7. What this talk is not 3
  • 8. What this talk is not New stuff 3-a
  • 9. What this talk is not New stuff Rocket Science 3-b
  • 10. What this talk is not New stuff Rocket Science Polemic 3-c
  • 12. What I’m hoping for A discussion 4-a
  • 13. What I’m hoping for A discussion Making things a tad more clear 4-b
  • 14. What I’m hoping for A discussion Making things a tad more clear ... or just less overlooked ? 4-c
  • 15. What I’m hoping for A discussion Making things a tad more clear ... or just less overlooked ? Not too boring 4-d
  • 16. What (functional, new things) you can do with Java 8 Lambda-expressions (String first, String second) -> Integer.compare(first.length(), second.length) Functional Interfaces Runnable r = () -> System.out.println("I am Runnable!"); Method references button.setOnAction(System.out::println); Constructor references List<String> labels = ... ; Stream<Button> buttonsStream = labels.stream().map(Button::new); Buttons[] buttonsArray = labels.stream().toArray(Button::new); int[]::new; 5
  • 17. The devil is in the details Optional<T>, Optional.of(), Optional.ofNullable(), Optional.empty() Default methods in interfaces. list.forEach(System.out::println) ... beware: SuperClasses win, Interfaces clash. ... And the standard library was not entirely rewritten (Path/Paths) Important topics : variable capture in closures, parallel execution. int[] counter = new int[1]; button.setOnAction(event -> counter[0]++); 6
  • 18. And also, Streams Any Collection has a stream() Stream.of() with a vararg, an array filter, map, flatMap, as well as plumbing: split, concat, limit Lazy processing, parallel() processing (you enforce statelessness) terminal reductions, e.g. reduce collector: HashSet<String> result = stream.collect(HashSet::new, HashSet::add, HashSet::addAll) Collector implementations (toList, toMap, ...) counting, maxBy, groupinBy, mapping, ... Beware: think about reuse. 7
  • 20. Interlude Does that make Java a functional programming language ? 8-a
  • 21. Interlude Does that make Java a functional programming language ? First class functions 8-b
  • 22. Interlude Does that make Java a functional programming language ? First class functions Technicalities 8-c
  • 23. Interlude Does that make Java a functional programming language ? First class functions Technicalities Does that make Java a Scala competitor ? 8-d
  • 24. Interlude Does that make Java a functional programming language ? First class functions Technicalities Does that make Java a Scala competitor ? Scala has never had a feature poverty problem. 8-e
  • 25. What you can’t do with Java 8 (yet) 1. Case classes 2. Pattern matching 3. Tail call elimination 4. Scoped access 5. Lazy keyword 6. Traits (well-scoped) 7. Rich Imports (local, aliased) 8. Macros 9. Backend (Miguel Garcia) 10. Specialization (Vlad Ureche) 11. Value classes 12. Implicits 13. Cake ! 9
  • 26. Collections The signatures of map Type classes & implicits Design goals 10
  • 28. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] 11-a
  • 29. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] But ... Type Constructor Polymorphism 11-b
  • 30. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] But ... Type Constructor Polymorphism trait TraversableLike[+Elem, +Coll[+x]] { def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem] def filter(p: Elem ⇒ Boolean): Coll[Elem] } 11-c
  • 31. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] But ... Type Constructor Polymorphism trait TraversableLike[+Elem, +Coll[+x]] { def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem] def filter(p: Elem ⇒ Boolean): Coll[Elem] } The idea that, whatever map needs, it will always deal with: 11-d
  • 32. The signatures of map def map[B](f: (A) ⇒ B) : Map[B] But ... Type Constructor Polymorphism trait TraversableLike[+Elem, +Coll[+x]] { def map[NewElem](f: Elem ⇒ NewElem): Coll[NewElem] def filter(p: Elem ⇒ Boolean): Coll[Elem] } The idea that, whatever map needs, it will always deal with: (Collection[Elements], Elements ⇒ OtherElements, Collection[OtherElements]) 11-e
  • 34. The signatures of map 12-a
  • 35. The signatures of map trait TraversableLike[+Elem, +Repr] { protected[this] def newBuilder: Builder[Elem, Repr] // deferred def foreach[U](f: Elem ⇒ U) // deferred def filter(p: Elem ⇒ Boolean): Repr = { val b = newBuilder foreach { elem <- if (p(elem)) b += elem } b.result } } class Builder[-Elem, +To] { def +=(elem: Elem): this.type = . . . def result(): To = . . . def clear() = . . . def mapResult[NewTo](f: To ⇒ NewTo): Builder[Elem, NewTo] = . . . } 12-b
  • 36. The signatures of map trait TraversableLike[+Elem, +Repr] { protected[this] def newBuilder: Builder[Elem, Repr] // deferred def foreach[U](f: Elem ⇒ U) // deferred def filter(p: Elem ⇒ Boolean): Repr = { val b = newBuilder foreach { elem <- if (p(elem)) b += elem } b.result } } class Builder[-Elem, +To] { def +=(elem: Elem): this.type = . . . def result(): To = . . . def clear() = . . . def mapResult[NewTo](f: To ⇒ NewTo): Builder[Elem, NewTo] = . . . } Why do we care ? Extensibility. 12-c
  • 37. The signatures of map (cont’d) 13
  • 38. The signatures of map (cont’d) 13-a
  • 39. The signatures of map (cont’d) def map[B, That](f: ((A,B)) ⇒ B) (implicit bf:CanBuildFrom[Map[A,B], B, That]):That 13-b
  • 40. The signatures of map (cont’d) def map[B, That](f: ((A,B)) ⇒ B) (implicit bf:CanBuildFrom[Map[A,B], B, That]):That Why ? 13-c
  • 41. The signatures of map (cont’d) def map[B, That](f: ((A,B)) ⇒ B) (implicit bf:CanBuildFrom[Map[A,B], B, That]):That Why ? Dealing with (Bitset, Int, BitSet) and (Bitset, String, Set[String]) 13-d
  • 42. The signatures of map (cont’d) def map[B, That](f: ((A,B)) ⇒ B) (implicit bf:CanBuildFrom[Map[A,B], B, That]):That Why ? Dealing with (Bitset, Int, BitSet) and (Bitset, String, Set[String]) Dealing with (Map[A, B], (A, B)) ⇒ (B, A), Map[B, A]) and (Map[A, B], (A, B)) ⇒ T, Iterable[T]) 13-e
  • 43. With Implicits trait CanBuildFrom[-Collection, -NewElem, +Result] { def apply(from: Collection): Builder[NewElem, Result] } trait TraversableLike[+A, +Repr] { def repr: Repr = . . . def foreach[U](f: A ⇒ U): Unit = . . . def map[B, To](f: A ⇒ B)(implicit cbf: CanBuildFrom[Repr, B, To]): To = { val b = cbf(repr) // get the builder from the CanBuildFrom instance for (x <- this) b += f(x) // transform element and add b.result } } 14
  • 44. trait SetLike[+A, +Repr] extends TraversableLike[A, Repr] { } trait BitSetLike[+This <: BitSetLike[This] with Set[Int]] extends SetLike[Int, This] {} trait Traversable[+A] extends TraversableLike[A, Traversable[A]] trait Set[+A] extends Traversable[A] with SetLike[A, Set[A]] class BitSet extends Set[Int] with BitSetLike[BitSet] object Set { implicit def canBuildFromSet[B] = new CanBuildFrom[Set[_], B, Set[B]] { def apply(from: Set[_]) = . . . } } object BitSet { implicit val canBuildFromBitSet = new CanBuildFrom[BitSet, Int, BitSet] { def apply(from: BitSet) = . . . } } 15