/** * Bastien Clément */ import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; class Mapper { static List map(List list, Function mapper) { List result = new ArrayList(); for (T item : list) { result.add(mapper.apply(item)); } return result; } } public class TE { public static void main(String[] args) { List list = Arrays.asList( new Match(Team.Blue, Team.Red, 1, 0), new Match(Team.Blue, Team.Green, 1, 1), new Match(Team.Blue, Team.Black, 3, 2), new Match(Team.Red, Team.Green, 0, 0), new Match(Team.Red, Team.Black, 1, 3), new Match(Team.Green, Team.Black, 2, 0) ); System.out.println("-- 1. Winners (lambda)"); System.out.println(Mapper.map(list, m -> m.winner())); System.out.println("-- 2. Winners (classic)"); System.out.println(Mapper.map(list, new Function() { @Override public Team apply(Match match) { return match.winner(); } })); System.out.println("-- 3. Unique winners"); System.out.println(list.stream() .map(Match::winner) .filter(w -> w != null) .distinct() .collect(Collectors.toList())); System.out.println("-- 4. Match with the highest number of goals"); System.out.println(Collections.max(list, Comparator.comparing(m -> m.scoreOne() + m.scoreTwo()))); System.out.println("-- 5. Total number of goals"); System.out.println(list.stream().collect(Collectors.summingInt(m -> m.scoreOne() + m.scoreTwo()))); System.out.println("-- 6. Best two teams"); Map scores = new HashMap<>(); for (Match m : list) { scores.merge(m.one(), m.pointsOne(), (a, b) -> a + b); scores.merge(m.two(), m.pointsTwo(), (a, b) -> a + b); } scores.entrySet() .stream() //.sorted(Comparator.comparing((Map.Entry entry) -> entry.getValue()).reversed()) // Nous sommes obligés de préciser le type pour utiliser Comparator.comparing suivi // de .reversed(), à la place, une lambda bien plus simple peut être utilisée. .sorted((a, b) -> b.getValue() - a.getValue()) .limit(2) .map(e -> String.format("%-5s %d", e.getKey(), e.getValue())) .forEach(System.out::println); System.out.println("-- 7. Pascal's triangle"); Stream.iterate(Arrays.asList(1), last -> { List next = new ArrayList<>(); next.add(1); for (int i = 1; i < last.size(); i++) { // last.get est O(1) puisque last est une ArrayList, preuve: if (!(last instanceof RandomAccess)) throw new AssertionError(); next.add(last.get(i) + last.get(i - 1)); } next.add(1); return next; }).limit(7).forEach(System.out::println); } }