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);
    }

Popular Pragmatic topics Top

Razor54672
The answer to 3rd Problem of Chapter 5 (Making Choices) of “Practical Programming, Third Edition” seems incorrect in the given answer ke...
New
ianwillie
Hello Brian, I have some problems with running the code in your book. I like the style of the book very much and I have learnt a lot as...
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
sdmoralesma
Title: Web Development with Clojure, Third Edition - migrations/create not working: p159 When I execute the command: user=&gt; (create-...
New
jdufour
Hello! On page xix of the preface, it says there is a community forum "… for help if your’re stuck on one of the exercises in this book… ...
New
New
brian-m-ops
#book-python-testing-with-pytest-second-edition Hi. Thanks for writing the book. I am just learning so this might just of been an issue ...
New
jskubick
I found an issue in Chapter 7 regarding android:backgroundTint vs app:backgroundTint. How to replicate: load chapter-7 from zipfile i...
New
brunogirin
When running tox for the first time, I got the following error: ERROR: InterpreterNotFound: python3.10 I realised that I was running ...
New
gorkaio
root_layout: {PentoWeb.LayoutView, :root}, This results in the following following error: no “root” html template defined for PentoWeb...
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
siddhant3030
I’m thinking of buying a monitor that I can rotate to use as a vertical monitor? Also, I want to know if someone is using it for program...
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
poll poll Be sure to check out @Dusty’s article posted here: An Introduction to Alternative Keyboard Layouts It’s one of the best write-...
New
AstonJ
I have seen the keycaps I want - they are due for a group-buy this week but won’t be delivered until October next year!!! :rofl: The Ser...
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
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
mafinar
Crystal recently reached version 1. I had been following it for awhile but never got to really learn it. Most languages I picked up out o...
New
husaindevelop
Inside our android webview app, we are trying to paste the copied content from another app eg (notes) using navigator.clipboard.readtext ...
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 PragProg

View all threads ❯