dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: Code for "Chapter 7, Lazy Evaluations" in one file

Nothing special:

package chapter7;

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class BeingLazy_LazyEvaluations {

    private final static List<String> names = List.of("Brad", "Kate", "Kim", "Jack", "Joe", "Mike", "Susan", "George", "Robert", "Julia", "Parker", "Benson");
    
    // "lazy/fpij/Evaluation.java" on p. 127, p.128

    private static boolean evaluate(final int value) {
        System.out.println("evaluating ..." + value);
        simulateTimeConsumingOp(2000);
        return value > 100;
    }

    private static void simulateTimeConsumingOp(long time_ms) {
        try {
            Thread.sleep(time_ms);
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }
    }

    // "lazy/fpij/Evaluation.java" p. 127

    private static void eagerEvaluator(final boolean input1, final boolean input2) {
        System.out.println("eagerEvaluator called...");
        System.out.println("accept?: " + (input1 && input2));
    }

    // "lazy/fpij/Evaluation.java" p. 128

    private static void lazyEvaluator(final Supplier<Boolean> input1, final Supplier<Boolean> input2) {
        System.out.println("lazyEvaluator called...");
        System.out.println("accept?: " + (input1.get() && input2.get()));
    }

    // "lazy/fpij/LazyStreams.java" on p.130

    private static int length(final String name) {
        System.out.println("getting length for " + name);
        return name.length();
    }

    // "lazy/fpij/LazyStreams.java" on p.130

    private static String toUpper(final String name) {
        System.out.println("converting to uppercase: " + name);
        return name.toUpperCase();
    }

    // "lazy/fpij/Evaluation.java" on p.127

    @Test
    void evaluateEagerly() {
        eagerEvaluator(evaluate(1), evaluate(2));
    }

    // "lazy/fpij/Evaluation.java" on p.128

    @Test
    void evaluateLazily() {
        lazyEvaluator(() -> evaluate(1), () -> evaluate(2));
    }

    // "lazy/fpij/LazyStreams.java" on p.130
    // ".map(name -> toUpper(name))" replaced with ".map(LazyStreams::toUpper)"

    @Test
    void lazyStream() {
        final String firstNameWith3Letters =
                names.stream()
                        .filter(name -> length(name) == 3)
                        .map(BeingLazy_LazyEvaluations::toUpper)
                        .findFirst()
                        .orElse("");
        System.out.println(firstNameWith3Letters);
    }

    // lazy/fpij/LazyStreams.java on p.132
    // ".map(name -> toUpper(name))" replaced with ".map(LazyStreams::toUpper)"

    @Test
    void peekingIntoLaziness() {
        Stream<String> namesWith3Letters =
                names.stream()
                        .filter(name -> length(name) == 3)
                        .map(BeingLazy_LazyEvaluations::toUpper);
        System.out.println("Stream created, filtered, mapped...");
        System.out.println("ready to call findFirst...");
        final String firstNameWith3Letters =
                namesWith3Letters
                        .findFirst()
                        .orElse("");
        System.out.println(firstNameWith3Letters);
    }

}

Where Next?

Popular Pragmatic Bookshelf topics Top

johnp
Hi Brian, Looks like the api for tinydb has changed a little. Noticed while working on chapter 7 that the .purge() call to the db throws...
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
JohnS
I can’t setup the Rails source code. This happens in a working directory containing multiple (postgres) Rails apps. With: ruby-3.0.0 s...
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’m under the impression that when the reader gets to page 136 (“View Data with the Database Inspector”), the code SHOULD be able to buil...
New
adamwoolhether
I’m not quite sure what’s going on here, but I’m unable to have to containers successfully complete the Readiness/Liveness checks. I’m im...
New
digitalbias
Title: Build a Weather Station with Elixir and Nerves: Problem connecting to Postgres with Grafana on (page 64) If you follow the defau...
New
hazardco
On page 78 the following code appears: &lt;%= link_to ‘Destroy’, product, class: ‘hover:underline’, method: :delete, data: { confirm...
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
davetron5000
Hello faithful readers! If you have tried to follow along in the book, you are asked to start up the dev environment via dx/build and ar...
New

Other popular topics Top

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
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
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
foxtrottwist
A few weeks ago I started using Warp a terminal written in rust. Though in it’s current state of development there are a few caveats (tab...
New
mafinar
This is going to be a long an frequently posted thread. While talking to a friend of mine who has taken data structure and algorithm cou...
New
PragmaticBookshelf
Rails 7 completely redefines what it means to produce fantastic user experiences and provides a way to achieve all the benefits of single...
New
hilfordjames
There appears to have been an update that has changed the terminology for what has previously been known as the Taskbar Overflow - this h...
New
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: