Java) Lambda Expressions / Method References / Stream
This post was migrated from Tistory. You can find the original here.
Lambda Expressions
Method References
1
2
3
4
5
6
7
8
9
10
11
//A lambda expression that calls a constructor can also be converted into a method reference.
Supplier<MyClass> s = () -> new MyClass();
Supplier<MyClass> s = MyClass::new;
//For array creation
Function<Integer, int[]> f = x -> new int[x];
Function<Integer, int[]> f = int[]::new;
//Use the functional interface that matches the number of parameters.
BiFunction<Integer, String, MyClass> bf = (i, s) -> new MyClass(i,s);
BiFunction<Integer, String, MyClass> bf = MyClass::new;
Stream
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String[] args) {
ArrayList<Integer> t = new ArrayList<>();
t.add(3); t.add(5); t.add(7);
Iterator<Integer> tt = t.iterator();
while (tt.hasNext()){
System.out.println(tt.next());
}
while (tt.hasNext()){
System.out.println(tt.next());
}
}
Result
357
An iterator is single-use. Once you’ve read through all the elements in a collection, you can’t use it again — you have to create a new one if you need it again. A stream works the same way: once it’s used, it’s closed.
There are a lot of stream methods, so just search for what you need when you need it.
An operation that consumes the stream’s elements is called a terminal operation.
- Intermediate operations:
map(), flatMap()........ - Terminal operations:
reduce(), collect().......\collect() either implements a Collector or uses one of the pre-built static methods on Collectors.
+α
Arrays.sort worst case is n^2
Collections.sort worst case is nlogn
Any sort obviously needs a comparison basis (a comparator).
blabla
Poking around the classes, methods, and interfaces in Java’s base packages and tracing through the inheritance seems like good practice. Alongside learning how to use the methods, it can serve as a guide for how to structure and expose a class well.