limit(n) — takes the first n elements, then stops. takeWhile(predicate) — takes elements while a condition is true, then stops. Think of limit() as a countdown timer — after n ticks, it stops — while takeWhile() as eating until you encounter something you don't like.
limit():
1List<Integer> result = List.of(1,2,3,4,5).stream()2 .limit(3)3 .toList();4// [1, 2, 3]
takeWhile():
1List<Integer> result = List.of(1,2,3,4,5).stream()2 .takeWhile(x -> x < 3)3 .toList();4// [1, 2]
Key difference:
Performance considerations:
1// Real-world: top-N scores2List<Player> top10 = players.stream()3 .sorted(Comparator.comparing(Player::getScore).reversed())4 .limit(10)5 .collect(Collectors.toList());67// Real-world: process until threshold8List<SensorReading> readings = sensorData.stream()9 .takeWhile(r -> r.getValue() < THRESHOLD)10 .collect(Collectors.toList());