Based on a six month migration of C# code to Java 8, what is legacy lambda code likely to look like and what mistakes can be made.
Good use cases.
Bad use cases with solutions
Ugly use cases.
Streams and lambdas the good, the bad and the ugly
1. Streams and Lambdas – The Good, The Bad and the Ugly
Peter Lawrey
Higher Frequency Trading Ltd
2. Introduction
For the last 6 months, Higher Frequency Trading has been
porting a legacy C# application with over 25K lines of code
to Java.
We have translated many LINQ statements into Java 8
Stream + Lambda.
What are some common patterns and anti-patterns we
have seen?
3. Contains 2.0
if (list.stream().anyMatch(p -> p.getType() == Type.Cash)) {
4. Deep Copy
List<Position> newPositions = classPos.stream()
.map(Position::clone)
.collect(toList())
5. Validate all entries
positions.forEach(Position::validate);
Validate throws an InvalidStateException if invalid
10. To collect or not (anti-pattern)
getTrades().stream()
.filter(t -> getDate().equals(t.getInfo().getDate()))
.collect(toList())
.forEach(t -> trades.add(t.getInfo()));
11. To collect or not (solution)
List<Trade> trades = getTrades().stream()
.filter(t -> getDate().equals(t.getInfo().getDate()))
.map(t → t.getInfo())
.collect(Collectors.toList());
16. Top twenty words (Ugly)
List<String> words =
Files.lines(path).parallel()
.flatMap(line -> Arrays.asList(line.split("b")).stream())
.collect(groupingBy(w -> w, counting()))
.entrySet().stream()
.sorted(comparing(Map.Entry<String, Long>::getValue).reversed())
.limit(20)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
17. I must use streams (Ugly)
combinedList.addAll(
balances.stream().collect(Collectors.toList()));
List<Trade> allTrades = new ArrayList<>();
trades1.forEach(t -> allTrades.add(t));
trades2.forEach(t -> allTrades.add(t));
18. Optional denial
Position todayPos = newPos.stream()
.filter(pos -> pos.getCUSIP().equals(p.getCUSIP()))
.findFirst().orElse(null);
if (todayPos != null) {