SlideShare uma empresa Scribd logo
1 de 40
4. Обобщения и лямбды
Программирование на Java
Федор Лаврентьев
МФТИ, 2016
Массивы
Массив
int[] ints = new int[10];
assert ints.length == 10;
for (int i = 0; i < ints.length; ++i) {
ints[i] = i * i;
}
Object arr = ints; // Array is an object
final Object[] objects = new Object[1];
objects = new Object[1]; // WRONG
objects[0] = arr; // But right o_O
Инициализация массивов
double[] coeffs = {3.0, 4.0, 5.0};
int[][] intMatrix = new int[3][4];
// 0 -> [0, 0, 0, 0]
// 1 -> [0, 0, 0, 0]
// 2 -> [0, 0, 0, 0]
char[][] words = {{‘a’, ‘b’, ’c’}, {‘d’, ‘e’}};
// 0 -> [‘a’, ‘b’, ‘c’]
// 1 -> [‘d’, ‘e’]
Многомерный массив
int[][] intChain = new int[3][];
// 0 -> null
// 1 -> null
// 2 -> null
for (int i = 0; i < intChain.length; ++i) {
intChain[i] = new int[i ** i];
}
// 0 -> []
// 1 -> [0]
// 2 -> [0, 0, 0, 0]
Обобщённые типы
Подробнее здесь:
https://docs.oracle.com/javase/tutorial/java/generics/index.html
Логика не зависит от типов аргументов
public class Pair {
final Object left;
final Object right;
public Pair(Object left, Object right) {
this.left = left;
this.right = right;
}
public Object getLeft() { return left; }
public Object getRight() { return right; }
}
Уточнение типов усложняет код
Pair pair = new Pair(42, “Forty two”);
Object leftObj = pair.getLeft();
Integer left = (Integer) leftObj;
String right = (String) pair.getRight();
Приведение типов потенциально опасно
public long extractLongLeft(Pair pair) {
Object leftObj = pair.getLeft;
if (!(leftObj instanceof Long)) {
throw new IllegalArgumentException();
}
Long leftLong = (Long) leftObj;
return leftLong.longValue(); // Unnecessary
}
Generics (обобщения)
public class Pair<A, B> {
private final A left;
private final B right;
public Pair(A left, B right) {
this.left = left;
this.right = right;
}
public A getLeft() { return left; }
public B getRight() { return right; }
}
Generics (обобщения)
Pair<Integer, String> p1 =
new Pair<Integer, String> (42, “Forty two”);
String right1 = p1.getRight(); // “Forty two”
Pair<Long, String> p2 = new Pair<>(0L, “Null”);
Long left1 = p2.getLeft(); // 0L
Generics: Go deeper
public static <A, B> Pair<A, B> pair(A a, B b) {
return new Pair<>(a, b);
}
Pair<Pair<String, Double>, Pair<Long, Byte>> p =
pair(
pair(“Foo”, 3.14),
pair(Long.MAX_VALUE, Byte.MAX_VALUE)
);
Pair rawPair = p; // Generic types lost
Подтипы
public interface Comparable<T> {
boolean geq(T other) default {
this.hashCode() >= other.hashCode();
}
}
public class Comparables {
public static <T extends Comparable> T min(T a, T b) {
if (a.geq(b)) return b else return a;
}
public static <T extends Comparable> T max(T a, T b) {
if (a.geq(b)) return a else return b;
}
}
Подтипы
import static Comparables.*;
class SortedPair<T extends Comparable>
extends Pair<T, T> {
public SortedPair(T a, T b) {
super(min(a, b), max(a, b))
}
}
Wildcard
public class Pairs {
public static <T> T toLeft(Pair<T, ?> pair) {
return pair.getLeft();
}
public static <T> T toRight(Pair<? extends Object, T> pair) {
return pair.getRight()
}
}
public class Zoo {
void addAnimal(Animal animal) { ... }
void addAnimals(List<? extends Animal> animals) { ... }
void addAnimals(List<Dog> dogs) { ... }
}
Ограничения обобщений
public class Pair<A, B> {
private static final A DEFAULT_LEFT;
public static <T> Pair<int, T> empty() {
return new Pair<>(0, new T());
}
public Pair<A, B>[] times(int n) {
Pair<A, B>[] pairs = new Pair<>[n];
...
}
public static boolean animalsEquals(Pair<Animal, Animal> pair) {
if (pair instanceof Pair<Dog, Dog>) {
Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair;
}
}
}
Ограничения обобщений
public class Pair<A, B> {
private static final A DEFAULT_LEFT; // WRONG
public static <T> Pair<int, T> empty() {
return new Pair<>(0, new T());
}
public Pair<A, B>[] times(int n) {
Pair<A, B>[] pairs = new Pair<>[n];
...
}
public static boolean animalsEquals(Pair<Animal, Animal> pair) {
if (pair instanceof Pair<Dog, Dog>) {
Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair;
}
}
}
Ограничения обобщений
public class Pair<A, B> {
private static final A DEFAULT_LEFT; // WRONG
public static <T> Pair<int, T> empty() { // WRONG
return new Pair<>(0, new T());
}
public Pair<A, B>[] times(int n) {
Pair<A, B>[] pairs = new Pair<>[n];
...
}
public static boolean animalsEquals(Pair<Animal, Animal> pair) {
if (pair instanceof Pair<Dog, Dog>) {
Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair;
}
}
}
Ограничения обобщений
public class Pair<A, B> {
private static final A DEFAULT_LEFT; // WRONG
public static <T> Pair<int, T> empty() { // WRONG
return new Pair<>(0, new T()); // WRONG
}
public Pair<A, B>[] times(int n) {
Pair<A, B>[] pairs = new Pair<>[n];
...
}
public static boolean animalsEquals(Pair<Animal, Animal> pair) {
if (pair instanceof Pair<Dog, Dog>) {
Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair;
}
}
}
Ограничения обобщений
public class Pair<A, B> {
private static final A DEFAULT_LEFT; // WRONG
public static <T> Pair<int, T> empty() { // WRONG
return new Pair<>(0, new T()); // WRONG
}
public Pair<A, B>[] times(int n) { // WRONG
Pair<A, B>[] pairs = new Pair<>[n]; // WRONG
...
}
public static boolean animalsEquals(Pair<Animal, Animal> pair) {
if (pair instanceof Pair<Dog, Dog>) {
Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair;
}
}
}
Ограничения обобщений
public class Pair<A, B> {
private static final A DEFAULT_LEFT; // WRONG
public static <T> Pair<int, T> empty() { // WRONG
return new Pair<>(0, new T()); // WRONG
}
public Pair<A, B>[] times(int n) { // WRONG
Pair<A, B>[] pairs = new Pair<>[n]; // WRONG
...
}
public static boolean animalsEquals(Pair<Animal, Animal> pair) {
if (pair instanceof Pair<Dog, Dog>) { // WRONG
Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair;
}
}
}
Ограничения обобщений
public class Pair<A, B> {
private static final A DEFAULT_LEFT; // WRONG
public static <T> Pair<int, T> empty() { // WRONG
return new Pair<>(0, new T()); // WRONG
}
public Pair<A, B>[] times(int n) { // WRONG
Pair<A, B>[] pairs = new Pair<>[n]; // WRONG
...
}
public static boolean animalsEquals(Pair<Animal, Animal> pair) {
if (pair instanceof Pair<Dog, Dog>) { // WRONG
Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; // WRONG
}
}
}
Лямбды
Функциональный интерфейс
public interface Runnable {
void run();
}
public class HelloRunnable implements Runnable {
@Override
public void run() {
System.out.println(“Hello!”);
}
}
Thread t = new Thread(new HelloRunnable());
t.start();
Функциональный интерфейс
public interface Runnable {
void run();
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(“Hello!”);
}
});
t.start();
Функциональный интерфейс
public interface Runnable {
void run();
}
Thread t = new Thread(() -> {
System.out.println(“Hello!”);
});
t.start();
Функциональный интерфейс
@FunctionalInterface
public interface Runnable {
void run();
}
Thread t = new Thread(() -> {
System.out.println(“Hello!”);
});
t.start();
Лямбда-выражение
@FunctionalInterface
interface Comparator<T> {
int compare (T first, T second);
}
Comparator<String> с1 =
(String a, String b) -> a.length() – b.length();
Comparator<String> c2 = (a, b) -> a.length() – b.length();
Comparator<String> c3 = (a, b) -> {
int lengthA = (a == null) ? 0 : a.length();
int lengthB = (b == null) ? 0 : b.length();
return lengthA – lengthB;
}
Применение лямбда-функций
public class Comparators {
public static int firstCharDiff(String a, String b) {
return a.charAt(0) - b.charAt(0)
}
public static Comparator<String> byNthLetter(int n) {
return (a, b) -> a.charAt(n-1) – b.charAt(n-1);
}
public static <T> void sort<T>
(T[] array, Comparator<T> comparator) { ... }
}
String[] strings = {“burr”, “yamm”, “foorr”};
Comparators.sort(Comparators::firstCharDiff);
Comparators.sort(Comparators.byNthLetter(2));
Основные структуры данных
Упорядоченный список (List)
List<Dog> dogs = Arrays.asList(
new Dog(“Billy”, “Bloodhound”),
new Dog(“Jackie”, “Bulldog”)
);
List<Animal> animals = new ArrayList<>(4);
animals.addAll(dogs);
animals.add(0, new Dog(“Pooker”, “Mongrel”));
animals.add(new Cat(“Snowee”, “Birman”));
List<Cat> cats = new LinkedList<>();
cats.add(new Cat(“Snowee”, “Birman”));
animals.containsAll(cats); // true
animals.get(0); // Pooker
List processing
List<Animal> animals = ...;
int totalTeeth = 0
for (int i = 0; i <= animals.size(); ++i) {
Animal a = animals.get(i);
if (!(a instanceof Dog)) {
continue;
}
Dog d = (Dog) a;
totalTeeth += d.getTeethCount();
}
Stream
List<Animal> animals = ...;
Stream<Animal> stream = animals.stream();
int totalTeeth = stream
.filter(a -> a instanceof Dog) // Stream<Animal>
.map(a -> (Dog) a) // Stream<Dog>
.mapToInt(Dog::getTeethCount) // IntStream
.sum(); // int
Уникальное множество (Set)
Set<Set> unique = new TreeSet(“Billy”, “Annett”, “Jane”, “Мишаня”,
“Pooker”, “Billy”);
unique.size(); // 5 (не 6!)
unique.headSet(“July”).foreach(System.out::println);
// Annett, Billy, Jane
unique.contains(“Annett”); // true
Отображение Словарь (Map)
Map<String, Animal> byName = new HashMap<>();
animals.stream()
.foreach(a -> byName.put(a.getName(), a))
byName.contains(“Bloody Joe”); // false
Animal pooker = byName.get(“Pooker”);
byName.entrySet().foreach(System.out::println);
// random order
Iterable
interface Iterable<T> {
Iterator<T> iterator();
Spliterator<T> spliterator();
void foreach(Consumer<? super T> consumer>);
}
List<Animal> animals = ...;
for (Iterator<Animal> it = animals.iterator();it.hasNext();) {
Animal a = it.next();
...
}
for (Animal a: animals) { ... }
animals.foreach(a -> ...)
Deeper – Lazy Iterator example
class DataBaseIterator<T> implements Iterator<T> {
private final int maxId;
private final Connection conn;
private int currentId = 0;
private final Mapper<Query, T> mapper;
DataBaseIterator(Connection conn, Mapper<Query, T> mapper) {
this.conn = conn;
this.mapper = mapper;
maxId = conn.queryInt(“select max(id) from t”);
}
public boolean hasNext() {
return currentId <= maxId;
}
public T next() {
return conn
.query(“select * from t where id = ?”, currentId++)
.map(mapper);
}
}
http://www.falkhausen.de/en/diagram/html/java.util.Collection.html
http://www.karambelkar.info/downloads/java_collections/Java-Collections_Map-API-ImageMap.html
http://www.sergiy.ca/guide-to-selecting-appropriate-map-collection-in-java/

Mais conteúdo relacionado

Mais procurados

Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Paulo Morgado
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
About java
About javaAbout java
About javaJay Xu
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116Paulo Morgado
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...tdc-globalcode
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to knowTomasz Dziurko
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
The Macronomicon
The MacronomiconThe Macronomicon
The MacronomiconMike Fogus
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBtdc-globalcode
 
Expression trees in c#
Expression trees in c#Expression trees in c#
Expression trees in c#Oleksii Holub
 
TDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypeTDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypetdc-globalcode
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
 

Mais procurados (20)

Hammurabi
HammurabiHammurabi
Hammurabi
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
About java
About javaAbout java
About java
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
Expression trees in c#
Expression trees in c#Expression trees in c#
Expression trees in c#
 
TDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypeTDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hype
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 

Destaque

Programming Java - Lecture 02 - Objects - Lavrentyev Fedor
Programming Java - Lecture 02 - Objects - Lavrentyev FedorProgramming Java - Lecture 02 - Objects - Lavrentyev Fedor
Programming Java - Lecture 02 - Objects - Lavrentyev FedorFedor Lavrentyev
 
Industrial Programming Java - Lection Pack 01 - Building an application - Lav...
Industrial Programming Java - Lection Pack 01 - Building an application - Lav...Industrial Programming Java - Lection Pack 01 - Building an application - Lav...
Industrial Programming Java - Lection Pack 01 - Building an application - Lav...Fedor Lavrentyev
 
Programming Java - Lection 06 - Multithreading - Lavrentyev Fedor
Programming Java - Lection 06 - Multithreading - Lavrentyev FedorProgramming Java - Lection 06 - Multithreading - Lavrentyev Fedor
Programming Java - Lection 06 - Multithreading - Lavrentyev FedorFedor Lavrentyev
 
Programming Java - Lection 05 - Software Design - Lavrentyev Fedor
Programming Java - Lection 05 - Software Design - Lavrentyev FedorProgramming Java - Lection 05 - Software Design - Lavrentyev Fedor
Programming Java - Lection 05 - Software Design - Lavrentyev FedorFedor Lavrentyev
 
Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...
Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...
Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...Fedor Lavrentyev
 
Industrial Programming Java - Lection Pack 02 - Distributed applications - La...
Industrial Programming Java - Lection Pack 02 - Distributed applications - La...Industrial Programming Java - Lection Pack 02 - Distributed applications - La...
Industrial Programming Java - Lection Pack 02 - Distributed applications - La...Fedor Lavrentyev
 
Programming Java - Lection 03 - Classes - Lavrentyev Fedor
Programming Java - Lection 03 - Classes - Lavrentyev FedorProgramming Java - Lection 03 - Classes - Lavrentyev Fedor
Programming Java - Lection 03 - Classes - Lavrentyev FedorFedor Lavrentyev
 
Programming Java - Lection 01 - Basics - Lavrentyev Fedor
Programming Java - Lection 01 - Basics - Lavrentyev FedorProgramming Java - Lection 01 - Basics - Lavrentyev Fedor
Programming Java - Lection 01 - Basics - Lavrentyev FedorFedor Lavrentyev
 
Manejo de excepciones en vb
Manejo de excepciones en vbManejo de excepciones en vb
Manejo de excepciones en vbgerardd98
 
Top 15 Adventures Destinations You Should Try Out
 Top 15 Adventures Destinations You Should Try Out Top 15 Adventures Destinations You Should Try Out
Top 15 Adventures Destinations You Should Try OutTours In Abu Dhabi.Com
 
Manual poo-unidad-visual-basic
Manual poo-unidad-visual-basicManual poo-unidad-visual-basic
Manual poo-unidad-visual-basicgerardd98
 

Destaque (13)

Programming Java - Lecture 02 - Objects - Lavrentyev Fedor
Programming Java - Lecture 02 - Objects - Lavrentyev FedorProgramming Java - Lecture 02 - Objects - Lavrentyev Fedor
Programming Java - Lecture 02 - Objects - Lavrentyev Fedor
 
Industrial Programming Java - Lection Pack 01 - Building an application - Lav...
Industrial Programming Java - Lection Pack 01 - Building an application - Lav...Industrial Programming Java - Lection Pack 01 - Building an application - Lav...
Industrial Programming Java - Lection Pack 01 - Building an application - Lav...
 
Programming Java - Lection 06 - Multithreading - Lavrentyev Fedor
Programming Java - Lection 06 - Multithreading - Lavrentyev FedorProgramming Java - Lection 06 - Multithreading - Lavrentyev Fedor
Programming Java - Lection 06 - Multithreading - Lavrentyev Fedor
 
Programming Java - Lection 05 - Software Design - Lavrentyev Fedor
Programming Java - Lection 05 - Software Design - Lavrentyev FedorProgramming Java - Lection 05 - Software Design - Lavrentyev Fedor
Programming Java - Lection 05 - Software Design - Lavrentyev Fedor
 
Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...
Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...
Industrial Programming Java - Lection Pack 03 - Relational Databases - Lavren...
 
Industrial Programming Java - Lection Pack 02 - Distributed applications - La...
Industrial Programming Java - Lection Pack 02 - Distributed applications - La...Industrial Programming Java - Lection Pack 02 - Distributed applications - La...
Industrial Programming Java - Lection Pack 02 - Distributed applications - La...
 
Programming Java - Lection 03 - Classes - Lavrentyev Fedor
Programming Java - Lection 03 - Classes - Lavrentyev FedorProgramming Java - Lection 03 - Classes - Lavrentyev Fedor
Programming Java - Lection 03 - Classes - Lavrentyev Fedor
 
Programming Java - Lection 01 - Basics - Lavrentyev Fedor
Programming Java - Lection 01 - Basics - Lavrentyev FedorProgramming Java - Lection 01 - Basics - Lavrentyev Fedor
Programming Java - Lection 01 - Basics - Lavrentyev Fedor
 
Acuerdo gobierno portuarios 051012
Acuerdo gobierno portuarios 051012Acuerdo gobierno portuarios 051012
Acuerdo gobierno portuarios 051012
 
Manejo de excepciones en vb
Manejo de excepciones en vbManejo de excepciones en vb
Manejo de excepciones en vb
 
Historia de los computadores
Historia de los computadoresHistoria de los computadores
Historia de los computadores
 
Top 15 Adventures Destinations You Should Try Out
 Top 15 Adventures Destinations You Should Try Out Top 15 Adventures Destinations You Should Try Out
Top 15 Adventures Destinations You Should Try Out
 
Manual poo-unidad-visual-basic
Manual poo-unidad-visual-basicManual poo-unidad-visual-basic
Manual poo-unidad-visual-basic
 

Semelhante a Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor

6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
package lab7 public class SetOperations public static.pdf
package lab7     public class SetOperations  public static.pdfpackage lab7     public class SetOperations  public static.pdf
package lab7 public class SetOperations public static.pdfsyedabdul78662
 
Mixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMark Needham
 
Step 1 The Pair Class Many times in writing software we come across p.pdf
Step 1 The Pair Class Many times in writing software we come across p.pdfStep 1 The Pair Class Many times in writing software we come across p.pdf
Step 1 The Pair Class Many times in writing software we come across p.pdfformaxekochi
 
package com.test;public class Team {    private String teamId;.pdf
package com.test;public class Team {    private String teamId;.pdfpackage com.test;public class Team {    private String teamId;.pdf
package com.test;public class Team {    private String teamId;.pdfaparnacollection
 
ALE2014 let tests drive or let dijkstra derive
ALE2014 let tests drive or let dijkstra deriveALE2014 let tests drive or let dijkstra derive
ALE2014 let tests drive or let dijkstra deriveSanderSlideShare
 
import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfADITIEYEWEAR
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdfakkhan101
 
Team public class Team {    private String teamId;    priva.pdf
Team public class Team {    private String teamId;    priva.pdfTeam public class Team {    private String teamId;    priva.pdf
Team public class Team {    private String teamId;    priva.pdfDEEPAKSONI562
 
Scala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timeScala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timekarianneberg
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collectionsMyeongin Woo
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheetanand_study
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 

Semelhante a Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor (20)

Java Generics
Java GenericsJava Generics
Java Generics
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
package lab7 public class SetOperations public static.pdf
package lab7     public class SetOperations  public static.pdfpackage lab7     public class SetOperations  public static.pdf
package lab7 public class SetOperations public static.pdf
 
Google's Guava
Google's GuavaGoogle's Guava
Google's Guava
 
Mixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented language
 
Step 1 The Pair Class Many times in writing software we come across p.pdf
Step 1 The Pair Class Many times in writing software we come across p.pdfStep 1 The Pair Class Many times in writing software we come across p.pdf
Step 1 The Pair Class Many times in writing software we come across p.pdf
 
package com.test;public class Team {    private String teamId;.pdf
package com.test;public class Team {    private String teamId;.pdfpackage com.test;public class Team {    private String teamId;.pdf
package com.test;public class Team {    private String teamId;.pdf
 
ALE2014 let tests drive or let dijkstra derive
ALE2014 let tests drive or let dijkstra deriveALE2014 let tests drive or let dijkstra derive
ALE2014 let tests drive or let dijkstra derive
 
import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdf
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
Team public class Team {    private String teamId;    priva.pdf
Team public class Team {    private String teamId;    priva.pdfTeam public class Team {    private String teamId;    priva.pdf
Team public class Team {    private String teamId;    priva.pdf
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
 
Scala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timeScala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en time
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdf
 
The java language cheat sheet
The java language cheat sheetThe java language cheat sheet
The java language cheat sheet
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 

Último

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 

Último (20)

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 

Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor

  • 1. 4. Обобщения и лямбды Программирование на Java Федор Лаврентьев МФТИ, 2016
  • 3. Массив int[] ints = new int[10]; assert ints.length == 10; for (int i = 0; i < ints.length; ++i) { ints[i] = i * i; } Object arr = ints; // Array is an object final Object[] objects = new Object[1]; objects = new Object[1]; // WRONG objects[0] = arr; // But right o_O
  • 4. Инициализация массивов double[] coeffs = {3.0, 4.0, 5.0}; int[][] intMatrix = new int[3][4]; // 0 -> [0, 0, 0, 0] // 1 -> [0, 0, 0, 0] // 2 -> [0, 0, 0, 0] char[][] words = {{‘a’, ‘b’, ’c’}, {‘d’, ‘e’}}; // 0 -> [‘a’, ‘b’, ‘c’] // 1 -> [‘d’, ‘e’]
  • 5. Многомерный массив int[][] intChain = new int[3][]; // 0 -> null // 1 -> null // 2 -> null for (int i = 0; i < intChain.length; ++i) { intChain[i] = new int[i ** i]; } // 0 -> [] // 1 -> [0] // 2 -> [0, 0, 0, 0]
  • 7. Логика не зависит от типов аргументов public class Pair { final Object left; final Object right; public Pair(Object left, Object right) { this.left = left; this.right = right; } public Object getLeft() { return left; } public Object getRight() { return right; } }
  • 8. Уточнение типов усложняет код Pair pair = new Pair(42, “Forty two”); Object leftObj = pair.getLeft(); Integer left = (Integer) leftObj; String right = (String) pair.getRight();
  • 9. Приведение типов потенциально опасно public long extractLongLeft(Pair pair) { Object leftObj = pair.getLeft; if (!(leftObj instanceof Long)) { throw new IllegalArgumentException(); } Long leftLong = (Long) leftObj; return leftLong.longValue(); // Unnecessary }
  • 10. Generics (обобщения) public class Pair<A, B> { private final A left; private final B right; public Pair(A left, B right) { this.left = left; this.right = right; } public A getLeft() { return left; } public B getRight() { return right; } }
  • 11. Generics (обобщения) Pair<Integer, String> p1 = new Pair<Integer, String> (42, “Forty two”); String right1 = p1.getRight(); // “Forty two” Pair<Long, String> p2 = new Pair<>(0L, “Null”); Long left1 = p2.getLeft(); // 0L
  • 12. Generics: Go deeper public static <A, B> Pair<A, B> pair(A a, B b) { return new Pair<>(a, b); } Pair<Pair<String, Double>, Pair<Long, Byte>> p = pair( pair(“Foo”, 3.14), pair(Long.MAX_VALUE, Byte.MAX_VALUE) ); Pair rawPair = p; // Generic types lost
  • 13. Подтипы public interface Comparable<T> { boolean geq(T other) default { this.hashCode() >= other.hashCode(); } } public class Comparables { public static <T extends Comparable> T min(T a, T b) { if (a.geq(b)) return b else return a; } public static <T extends Comparable> T max(T a, T b) { if (a.geq(b)) return a else return b; } }
  • 14. Подтипы import static Comparables.*; class SortedPair<T extends Comparable> extends Pair<T, T> { public SortedPair(T a, T b) { super(min(a, b), max(a, b)) } }
  • 15. Wildcard public class Pairs { public static <T> T toLeft(Pair<T, ?> pair) { return pair.getLeft(); } public static <T> T toRight(Pair<? extends Object, T> pair) { return pair.getRight() } } public class Zoo { void addAnimal(Animal animal) { ... } void addAnimals(List<? extends Animal> animals) { ... } void addAnimals(List<Dog> dogs) { ... } }
  • 16. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; public static <T> Pair<int, T> empty() { return new Pair<>(0, new T()); } public Pair<A, B>[] times(int n) { Pair<A, B>[] pairs = new Pair<>[n]; ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  • 17. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { return new Pair<>(0, new T()); } public Pair<A, B>[] times(int n) { Pair<A, B>[] pairs = new Pair<>[n]; ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  • 18. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); } public Pair<A, B>[] times(int n) { Pair<A, B>[] pairs = new Pair<>[n]; ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  • 19. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); // WRONG } public Pair<A, B>[] times(int n) { Pair<A, B>[] pairs = new Pair<>[n]; ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  • 20. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); // WRONG } public Pair<A, B>[] times(int n) { // WRONG Pair<A, B>[] pairs = new Pair<>[n]; // WRONG ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  • 21. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); // WRONG } public Pair<A, B>[] times(int n) { // WRONG Pair<A, B>[] pairs = new Pair<>[n]; // WRONG ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { // WRONG Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  • 22. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); // WRONG } public Pair<A, B>[] times(int n) { // WRONG Pair<A, B>[] pairs = new Pair<>[n]; // WRONG ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { // WRONG Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; // WRONG } } }
  • 24. Функциональный интерфейс public interface Runnable { void run(); } public class HelloRunnable implements Runnable { @Override public void run() { System.out.println(“Hello!”); } } Thread t = new Thread(new HelloRunnable()); t.start();
  • 25. Функциональный интерфейс public interface Runnable { void run(); } Thread t = new Thread(new Runnable() { @Override public void run() { System.out.println(“Hello!”); } }); t.start();
  • 26. Функциональный интерфейс public interface Runnable { void run(); } Thread t = new Thread(() -> { System.out.println(“Hello!”); }); t.start();
  • 27. Функциональный интерфейс @FunctionalInterface public interface Runnable { void run(); } Thread t = new Thread(() -> { System.out.println(“Hello!”); }); t.start();
  • 28. Лямбда-выражение @FunctionalInterface interface Comparator<T> { int compare (T first, T second); } Comparator<String> с1 = (String a, String b) -> a.length() – b.length(); Comparator<String> c2 = (a, b) -> a.length() – b.length(); Comparator<String> c3 = (a, b) -> { int lengthA = (a == null) ? 0 : a.length(); int lengthB = (b == null) ? 0 : b.length(); return lengthA – lengthB; }
  • 29. Применение лямбда-функций public class Comparators { public static int firstCharDiff(String a, String b) { return a.charAt(0) - b.charAt(0) } public static Comparator<String> byNthLetter(int n) { return (a, b) -> a.charAt(n-1) – b.charAt(n-1); } public static <T> void sort<T> (T[] array, Comparator<T> comparator) { ... } } String[] strings = {“burr”, “yamm”, “foorr”}; Comparators.sort(Comparators::firstCharDiff); Comparators.sort(Comparators.byNthLetter(2));
  • 31. Упорядоченный список (List) List<Dog> dogs = Arrays.asList( new Dog(“Billy”, “Bloodhound”), new Dog(“Jackie”, “Bulldog”) ); List<Animal> animals = new ArrayList<>(4); animals.addAll(dogs); animals.add(0, new Dog(“Pooker”, “Mongrel”)); animals.add(new Cat(“Snowee”, “Birman”)); List<Cat> cats = new LinkedList<>(); cats.add(new Cat(“Snowee”, “Birman”)); animals.containsAll(cats); // true animals.get(0); // Pooker
  • 32. List processing List<Animal> animals = ...; int totalTeeth = 0 for (int i = 0; i <= animals.size(); ++i) { Animal a = animals.get(i); if (!(a instanceof Dog)) { continue; } Dog d = (Dog) a; totalTeeth += d.getTeethCount(); }
  • 33. Stream List<Animal> animals = ...; Stream<Animal> stream = animals.stream(); int totalTeeth = stream .filter(a -> a instanceof Dog) // Stream<Animal> .map(a -> (Dog) a) // Stream<Dog> .mapToInt(Dog::getTeethCount) // IntStream .sum(); // int
  • 34. Уникальное множество (Set) Set<Set> unique = new TreeSet(“Billy”, “Annett”, “Jane”, “Мишаня”, “Pooker”, “Billy”); unique.size(); // 5 (не 6!) unique.headSet(“July”).foreach(System.out::println); // Annett, Billy, Jane unique.contains(“Annett”); // true
  • 35. Отображение Словарь (Map) Map<String, Animal> byName = new HashMap<>(); animals.stream() .foreach(a -> byName.put(a.getName(), a)) byName.contains(“Bloody Joe”); // false Animal pooker = byName.get(“Pooker”); byName.entrySet().foreach(System.out::println); // random order
  • 36. Iterable interface Iterable<T> { Iterator<T> iterator(); Spliterator<T> spliterator(); void foreach(Consumer<? super T> consumer>); } List<Animal> animals = ...; for (Iterator<Animal> it = animals.iterator();it.hasNext();) { Animal a = it.next(); ... } for (Animal a: animals) { ... } animals.foreach(a -> ...)
  • 37. Deeper – Lazy Iterator example class DataBaseIterator<T> implements Iterator<T> { private final int maxId; private final Connection conn; private int currentId = 0; private final Mapper<Query, T> mapper; DataBaseIterator(Connection conn, Mapper<Query, T> mapper) { this.conn = conn; this.mapper = mapper; maxId = conn.queryInt(“select max(id) from t”); } public boolean hasNext() { return currentId <= maxId; } public T next() { return conn .query(“select * from t where id = ?”, currentId++) .map(mapper); } }

Notas do Editor

  1. Массив проинициалищирован Нельзя выйти за границы массива Массив это объект
  2. Diamond operator
  3. Generic method, Type Inference, Raw types, Runtime type erasure
  4. ровно 1 абстрактный метод, не учитываются обычные методы объекта и default-методы
  5. Type Inference
  6. Замыкание, ссылка на функцию, ссылка на конструктор – new, выбор при перегрузке – по совпадению аргументов
  7. Map-backed