DEV Community

loading...
Cover image for Solution: The verse with the maximum number of appearances

Solution: The verse with the maximum number of appearances

pazvanti profile image pazvanti ・2 min read

Problem: Given a poem, with each verse on a new line, Find the verse (or verses) that have the maximum number of appearances and how many times it appears in the text.

Solution:

public static List<Pair> max2(String fullText) throws Exception {
        // If there is no text provided, throw an exception
        if (fullText == null || fullText.isBlank()) throw new Exception("No text provided");

        // We split it by line separator so that we get all the verses. We also do a 'toLowerCase' so that
        // we analyze it case-insensitive
        String[] split = fullText.toLowerCase(Locale.ROOT).split("\n");

        // Create a List from the verses (so that we can use Streams
        // And a HashSet, so that we have each verse only once
        List<String> verses = Arrays.asList(split);
        Set<String> uniqueVerses = new HashSet<>(verses);

        // Now, let's process it
        return uniqueVerses.stream()
                // We map each line to a Pair that has the line and the frequency it appears in the text
                .map(line -> new Pair(line, Collections.frequency(verses, line)))

                // We collect it and group them by the number of appearances, now, we will have groups (Map) with the
                // Number of appearances as the key and the list of verses as the value
                .collect(Collectors.groupingBy(p -> p.getValue()))

                // We make the result a Stream so that we can find the MAX
                .entrySet().stream()

                // Get the group that has the maximum number of appearances
                .max(Comparator.comparingInt(p -> p.getKey().intValue()))

                // Retrieve the result and get the List. It will be a List of Pair<String, Integer>,
                // where the Key is the verse and the value is the number of appearances
                .get().getValue();
    }
Enter fullscreen mode Exit fullscreen mode

Conclusions:
Using the power of streams, we can easily manipulate our data set to do groupings, counting, and finding the maximum. No need for complex for-loops or external libraries.

Discussion (0)

Forem Open with the Forem app