Home >Java >javaTutorial >Item Give preference to functions without side effects in streams
Introduction to using streams:
Structuring of the calculation:
Side effects:
Example 1: Code with side effects
Map<String, Long> freq = new HashMap<>(); try (Stream<String> words = new Scanner(file).tokens()) { words.forEach(word -> { freq.merge(word.toLowerCase(), 1L, Long::sum); }); }
Problem: This code uses forEach to modify the external state (freq). It is iterative and does not take advantage of streams.
Example 2: Code without side effects
Map<String, Long> freq; try (Stream<String> words = new Scanner(file).tokens()) { freq = words.collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting())); }
Solution: Uses the Collectors.groupingBy collector to create the frequency table without changing the external state. Shorter, clearer and more efficient.
Appropriation of the streams API:
Collectors:
Example 3: Extracting a list of the ten most frequent words
List<String> topTen = freq.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .limit(10) .map(Map.Entry::getKey) .collect(Collectors.toList());
Explanation:
Complexity of the Collectors API:
Maps and collection strategies:
Example 4: Using toMap with merge function
Map<String, Long> freq; try (Stream<String> words = new Scanner(file).tokens()) { freq = words.collect(Collectors.toMap( String::toLowerCase, word -> 1L, Long::sum )); }
Explanation:
Example 5: Grouping albums by artist and finding the best-selling album
Map<Artist, Album> topAlbums = albums.stream() .collect(Collectors.toMap( Album::getArtist, Function.identity(), BinaryOperator.maxBy(Comparator.comparing(Album::sales)) ));
Explanation:
String Collection:
Collectors.joining to concatenate strings with optional delimiters.
Example 6: Concatenating strings with delimiter
String result = Stream.of("came", "saw", "conquered") .collect(Collectors.joining(", ", "[", "]"));
Explanation:
Conclusion:
The above is the detailed content of Item Give preference to functions without side effects in streams. For more information, please follow other related articles on the PHP Chinese website!