dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: Chapter 12

On page 200, the code can use boxed() instead of the (somewhat mysterious) maptoObject(e -> e)

One should also reveal to the reader that we are computing perfect numbers :joy:

package chapter12;

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

public class Chapter12 {

    // Confusing code on page 200
    // but with mapToObj(e -> e) replaced with boxed()

    private static List<Long> confusingCode(long number) {
        return LongStream.rangeClosed(1, number)
                .filter(i -> { //Bad Code, don't do this
                    long factor = 0;
                    for (int j = 1; j < i; j++) {
                        if (i % j == 0) {
                            factor += j;
                        }
                    }
                    return factor == i;
                })
                .boxed()
                .toList();
    }

    // Confusing code on page 201
    // but with mapToObj(e -> e) replaced with boxed()

    private static List<Long> refactoredConfusingCode(long number) {
        return LongStream.range(1, number)
                .filter(i -> LongStream.range(1, i) //Not good
                        .filter(j -> i % j == 0)
                        .sum() == i)
                .boxed()
                .toList();
    }

    // Nonconfusing code on page 201, in two methods

    private static Long sumOfDivisors(long number) {
        return LongStream.range(1, number)
                .filter(i -> number % i == 0)
                .sum();
    }

    // Create list of those x <= limit such that the sum of the divisors of x equals x
    // https://en.wikipedia.org/wiki/Perfect_number
    // https://oeis.org/A000396

    private static List<Long> nonConfusingCode(long limit) {
        return LongStream.rangeClosed(1, limit)
                .filter(i -> sumOfDivisors(i) == i)
                .boxed()
                .toList();
    }

    // A record to pass data along the stream

    private record InAndOut(Long in, List<Long> out) {
        public String toString() {
            return "f(" + in + ")=[" + out.stream().map(it -> Long.toString(it)).collect(Collectors.joining(",")) + "]";
        }
    }

    private static String exerciseCode(Function<Long, List<Long>> f, List<Long> input) {
        return input.stream()
                .map(it -> new InAndOut(it, f.apply(it)))
                .map(InAndOut::toString)
                .collect(Collectors.joining(", "));
    }

    @Test
    public void exerciseAllCode() {
        var input = List.of(0L, 1L, 2L, 10L, 13L, 100L, 1000L, 10000L);
        {
            String str = exerciseCode(Chapter12::confusingCode, input);
            System.out.println(str);
        }
        {
            String str = exerciseCode(Chapter12::refactoredConfusingCode, input);
            System.out.println(str);
        }
        {
            String str = exerciseCode(Chapter12::nonConfusingCode, input);
            System.out.println(str);
        }
    }
}

Where Next?

Popular Pragmatic Bookshelf topics Top

jon
Some minor things in the paper edition that says “3 2020” on the title page verso, not mentioned in the book’s errata online: p. 186 But...
New
iPaul
page 37 ANTLRInputStream input = new ANTLRInputStream(is); as of ANTLR 4 .8 should be: CharStream stream = CharStreams.fromStream(i...
New
johnp
Running the examples in chapter 5 c under pytest 5.4.1 causes an AttributeError: ‘module’ object has no attribute ‘config’. In particula...
New
jamis
The following is cross-posted from the original Ray Tracer Challenge forum, from a post by garfieldnate. I’m cross-posting it so that the...
New
herminiotorres
Hi! I know not the intentions behind this narrative when called, on page XI: mount() |&gt; handle_event() |&gt; render() but the correc...
New
brunogirin
When I run the coverage example to report on missing lines, I get: pytest --cov=cards --report=term-missing ch7 ERROR: usage: pytest [op...
New
brunogirin
When installing Cards as an editable package, I get the following error: ERROR: File “setup.py” not found. Directory cannot be installe...
New
taguniversalmachine
It seems the second code snippet is missing the code to set the current_user: current_user: Accounts.get_user_by_session_token(session["...
New
rainforest
Hi, I’ve got a question about the implementation of PubSub when using a Phoenix.Socket.Transport behaviour rather than channels. Before ...
New
mcpierce
@mfazio23 I’ve applied the changes from Chapter 5 of the book and everything builds correctly and runs. But, when I try to start a game,...
New

Other popular topics Top

AstonJ
A thread that every forum needs! Simply post a link to a track on YouTube (or SoundCloud or Vimeo amongst others!) on a separate line an...
New
AstonJ
If it’s a mechanical keyboard, which switches do you have? Would you recommend it? Why? What will your next keyboard be? Pics always w...
New
AstonJ
Curious to know which languages and frameworks you’re all thinking about learning next :upside_down_face: Perhaps if there’s enough peop...
New
AstonJ
You might be thinking we should just ask who’s not using VSCode :joy: however there are some new additions in the space that might give V...
New
AstonJ
Do the test and post your score :nerd_face: :keyboard: If possible, please add info such as the keyboard you’re using, the layout (Qw...
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
Exadra37
I am asking for any distro that only has the bare-bones to be able to get a shell in the server and then just install the packages as we ...
New
PragmaticBookshelf
Author Spotlight Mike Riley @mriley This month, we turn the spotlight on Mike Riley, author of Portable Python Projects. Mike’s book ...
New
AstonJ
If you want a quick and easy way to block any website on your Mac using Little Snitch simply… File &gt; New Rule: And select Deny, O...
New
CommunityNews
A Brief Review of the Minisforum V3 AMD Tablet. Update: I have created an awesome-minisforum-v3 GitHub repository to list information fo...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: