[JAVA] Item 45: Use streams judiciously

45. Stream should be used with caution

package tryAny.effectiveJava;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Anagrams {
    public static void main(String[] args) throws IOException {
        File dictionary = new File("/application/gradle/getting-started.html");
        int minGroupSize = 2;

        Map<String, Set<String>> groups = new HashMap<>();

        //Example 1 start
        try (Scanner s = new Scanner(dictionary)) {
            while (s.hasNext()) {
                String word = s.next();
                groups.computeIfAbsent(alphabetize(word), (unused) -> new TreeSet<>()).add(word);
            }
        }
        for (Set<String> group : groups.values()) {
            if (group.size() >= minGroupSize) {
                System.out.println(group.size() + ":" + group);
            }
        }
        //Example 1 end

        //Example 2 start(This is an anagram for each line, so the result is different from Example 1.)
        Path dictionary2 = Paths.get("/application/gradle/getting-started.html");
        try (Stream<String> words = Files.lines(dictionary2)) {
            words.collect(Collectors.groupingBy(word -> word.chars().sorted()
                    .collect(StringBuilder::new, (sb, c) -> sb.append((char) c), StringBuilder::append).toString()))
                    .values().stream().filter(group -> group.size() >= minGroupSize)
                    .map(group -> group.size() + ":" + group).forEach(System.out::println);
        }
        //Example 2 end

        //Example 3 start (same result as Example 2)
        try (Stream<String> words = Files.lines(dictionary2)) {
            words.collect(Collectors.groupingBy(word -> alphabetize(word)))
            .values().stream()
                    .filter(group -> group.size() >= minGroupSize)
                    .forEach(g -> System.out.println(g.size() + ":" + g));
        }
        //Example 3 end
    }

    private static String alphabetize(String s) {
        char[] a = s.toCharArray();
        Arrays.sort(a);
        return new String(a);
    }
}
package tryAny.effectiveJava;

public class CharStream {
    public static void main(String[] args) {
        "Hello, world!".chars().forEach(System.out::print);
        //72101108108111443211911111410810033 is displayed

        System.out.println();

        "Hello, world!".chars().forEach(x -> System.out.print((char) x));
        // Hello, world!Is displayed
    }
}
package tryAny.effectiveJava;

import static java.math.BigInteger.*;

import java.math.BigInteger;
import java.util.stream.Stream;

public class MersennePrimes {
    public static void main(String[] args) {
        primes().map(p -> TWO.pow(p.intValueExact()).subtract(ONE)).filter(mersenne -> mersenne.isProbablePrime(50))
                .limit(20)
                // .forEach(System.out::println);
                .forEach(mp -> System.out.println(mp.bitLength() + ":" + mp));
    }

    static Stream<BigInteger> primes() {
        return Stream.iterate(TWO, BigInteger::nextProbablePrime);
    }
}

Recommended Posts

Item 45: Use streams judiciously
Item 52: Use overloading judiciously
Item 83: Use lazy initialization judiciously
Item 66: Use native methods judiciously
Item 48: Use caution when making streams parallel
Item 55: Return optionals judiciously
Item 26: Don't use raw types
Item 32: Combine generics and varargs judiciously
Item 46: Prefer side-effect-free functions in streams
Item 59: Know and use the libraries
Item 40: Consistently use the Override annotation
Item 69: Use exceptions only for exceptional conditions
Item 41: Use marker interfaces to define types
Item 36: Use EnumSet instead of bit fields
Item 71: Avoid unnecessary use of checked exceptions
Item 37: Use EnumMap instead of ordinal indexing
Item 72: Favor the use of standard exceptions