dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: Nicer code pf page 7

I suggest this nicer code for the Statistics.java on page on page 70 (we are doing streams after).

Not using a main() but a JUnit 5 Test Case:

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.averagingDouble;
import static java.util.stream.Collectors.summarizingDouble;

public class TransformingData {

    record Pair(String str, Number num) {

        public String toString() {
            return str + ": " + num;
        }
    }

    @Test
    public void statistics() {
        var statistics = Person.getPeople().stream()
                .collect(
                        summarizingDouble(person -> person.emailAddresses().size()));
        var pairs = new ArrayList<Pair>();
        pairs.add(new Pair("Number of people", statistics.getCount()));
        pairs.add(new Pair("Number of email addresses", statistics.getSum()));
        pairs.add(new Pair("Average number of email addresses", statistics.getAverage()));
        pairs.add(new Pair("Max number of email addresses", statistics.getMax()));
        pairs.add(new Pair("Min number of email addresses", statistics.getMin()));
        String res = pairs.stream().map(Pair::toString).collect(Collectors.joining("\n"));
        System.out.println(res);
    }
}

Similary for the next exercises

    record PairB(String str, Boolean b) {

        public String toString() {
            return str + ": " + b;
        }
    }

    public void printPairsB(List<PairB> pairs) {
        var res = pairs.stream().map(PairB::toString).collect(Collectors.joining("\n"));
        System.out.println(res);
    }

    @Test
    public void checkingForCriteriaAny() {
        List<Person> people = Person.getPeople();
        var pairs = new ArrayList<PairB>();
        pairs.add(new PairB(
                "Anyone has email address: ",
                people.stream().anyMatch(person -> person.emailAddresses().size() > 0)));
        pairs.add(new PairB(
                "Anyone has more than 10 email address: ",
                people.stream().anyMatch(person -> person.emailAddresses().size() > 10)));
        printPairsB(pairs);
    }

    @Test
    public void checkingForCriteriaAll() {
        List<Person> people = Person.getPeople();
        var pairs = new ArrayList<PairB>();
        pairs.add(new PairB(
                "Everyone has at least one email address: ",
                people.stream().allMatch(person -> person.emailAddresses().size() > 0)));
        pairs.add(new PairB(
                "Everyone has zero or more email address: ",
                people.stream().allMatch(person -> person.emailAddresses().size() >= 0)));
        printPairsB(pairs);
    }

And even the next

    record PairN(String str, Number num) {

        public String toString() {
            return str + ": " + num;
        }
    }

    public void printPairsN(List<PairN> pairs) {
        var res = pairs.stream().map(PairN::toString).collect(Collectors.joining("\n"));
        System.out.println(res);
    }

    @Test
    public void partitioning() {
        List<Person> people = Person.getPeople();
        Map<Boolean, List<Person>> partitions =
                people.stream()
                        .collect(partitioningBy(person -> person.emailAddresses().size() > 1));
        var pairs = new ArrayList<PairN>();
        pairs.add(new PairN("Number of people with at most one email address", partitions.get(false).size()));
        pairs.add(new PairN("Number of people with multiple email addresses" , partitions.get(true).size()));
        printPairsN(pairs);
    }

Where Next?

Popular Pragmatic Bookshelf topics Top

jimschubert
In Chapter 3, the source for index introduces Config on page 31, followed by more code including tests; Config isn’t introduced until pag...
New
brianokken
Many tasks_proj/tests directories exist in chapters 2, 3, 5 that have tests that use the custom markers smoke and get, which are not decl...
New
yulkin
your book suggests to use Image.toByteData() to convert image to bytes, however I get the following error: "the getter ‘toByteData’ isn’t...
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
New
adamwoolhether
When trying to generate the protobuf .go file, I receive this error: Unknown flag: --go_opt libprotoc 3.12.3 MacOS 11.3.1 Googling ...
New
AndyDavis3416
@noelrappin Running the webpack dev server, I receive the following warning: ERROR in tsconfig.json TS18003: No inputs were found in c...
New
fynn
This is as much a suggestion as a question, as a note for others. Locally the SGP30 wasn’t available, so I ordered a SGP40. On page 53, ...
New
mert
AWDWR 7, page 152, page 153: Hello everyone, I’m a little bit lost on the hotwire part. I didn’t fully understand it. On page 152 @rub...
New
Henrai
Hi, I’m working on the Chapter 8 of the book. After I add add the point_offset, I’m still able to see acne: In the image above, I re...
New

Other popular topics Top

Exadra37
I am thinking in building or buy a desktop computer for programing, both professionally and on my free time, and my choice of OS is Linux...
New
PragmaticBookshelf
Design and develop sophisticated 2D games that are as much fun to make as they are to play. From particle effects and pathfinding to soci...
New
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
Thanks to @foxtrottwist’s and @Tomas’s posts in this thread: Poll: Which code editor do you use? I bought Onivim! :nerd_face: https://on...
New
New
Maartz
Hi folks, I don’t know if I saw this here but, here’s a new programming language, called Roc Reminds me a bit of Elm and thus Haskell. ...
New
AstonJ
If you get Can't find emacs in your PATH when trying to install Doom Emacs on your Mac you… just… need to install Emacs first! :lol: bre...
New
PragmaticBookshelf
Author Spotlight: Sophie DeBenedetto @SophieDeBenedetto The days of the traditional request-response web application are long gone, b...
New
AstonJ
Curious what kind of results others are getting, I think actually prefer the 7B model to the 32B model, not only is it faster but the qua...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: