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

abtin
page 20: … protoc command… I had to additionally run the following go get commands in order to be able to compile protobuf code using go...
New
Razor54672
The answer to 3rd Problem of Chapter 5 (Making Choices) of “Practical Programming, Third Edition” seems incorrect in the given answer ke...
New
Alexandr
Hi everyone! There is an error on the page 71 in the book “Programming machine learning from coding to depp learning” P. Perrotta. You c...
New
simonpeter
When I try the command to create a pair of migration files I get an error. user=&gt; (create-migration "guestbook") Execution error (Ill...
New
mikecargal
Title: Hands-On Rust (Chap 8 (Adding a Heads Up Display) It looks like ​.with_simple_console_no_bg​(SCREEN_WIDTH*2, SCREEN_HEIGHT*2...
New
raul
Page 28: It implements io.ReaderAt on the store type. Sorry if it’s a dumb question but was the io.ReaderAt supposed to be io.ReadAt? ...
New
swlaschin
The book has the same “Problem space/Solution space” diagram on page 18 as is on page 17. The correct Problem/Solution space diagrams ar...
New
dsmith42
Hey there, I’m enjoying this book and have learned a few things alredayd. However, in Chapter 4 I believe we are meant to see the “&gt;...
New
jonmac
The allprojects block listed on page 245 produces the following error when syncing gradle: “org.gradle.api.GradleScriptException: A prob...
New
dachristenson
I’ve got to the end of Ch. 11, and the app runs, with all tabs displaying what they should – at first. After switching around between St...
New

Other popular topics Top

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
DevotionGeo
I know that these benchmarks might not be the exact picture of real-world scenario, but still I expect a Rust web framework performing a ...
New
axelson
I’ve been really enjoying obsidian.md: It is very snappy (even though it is based on Electron). I love that it is all local by defaul...
New
AstonJ
I’ve been hearing quite a lot of comments relating to the sound of a keyboard, with one of the most desirable of these called ‘thock’, he...
New
PragmaticBookshelf
Rust is an exciting new programming language combining the power of C with memory safety, fearless concurrency, and productivity boosters...
New
Exadra37
On modern versions of macOS, you simply can’t power on your computer, launch a text editor or eBook reader, and write or read, without a ...
New
AstonJ
Just done a fresh install of macOS Big Sur and on installing Erlang I am getting: asdf install erlang 23.1.2 Configure failed. checking ...
New
AstonJ
Biggest jackpot ever apparently! :upside_down_face: I don’t (usually) gamble/play the lottery, but working on a program to predict the...
New
New
AstonJ
If you’re getting errors like this: psql: error: connection to server on socket “/tmp/.s.PGSQL.5432” failed: No such file or directory ...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: