Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Introduction to Functional Programming Java's Functional Toolset Function Shapes

Andre Kucharzyk
Andre Kucharzyk
4,479 Points

Why Main.createIssue() function is called?

Hi! Even though I don't have null member of the list function Main.createIssue() is called for every single word from the list. Why?

package com.functional;

import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream;

public class Main {

public static void yell(String word){
        Objects.requireNonNull(word, "Created issue" + Main.createIssue());
    System.out.printf("%s!!!! %n", word.toUpperCase());
}

private static String createIssue() {
    System.out.println("Some external API call to a bugtracker");
    return "#23123";
}

public static void main(String[] args) {
    // write your code here
    List<String> bodyParts = Arrays.asList(
            "Dupa",
            "Nie dupa",
            "Znowu nie dupa",
            "Ręka",
            "Noga",
            "Mózg na ścianie"
    );

    bodyParts.forEach(Main::yell);

}

}

CONSOLE:

Some external API call to a bugtracker DUPA!!!! Some external API call to a bugtracker NIE DUPA!!!! Some external API call to a bugtracker ZNOWU NIE DUPA!!!! Some external API call to a bugtracker RĘKA!!!! Some external API call to a bugtracker NOGA!!!! Some external API call to a bugtracker MÓZG NA ŚCIANIE!!!!

Process finished with exit code 0

aterleck
aterleck
4,328 Points

Hello, Objects.requireNonNull checks if the objects is not null. It means that if you have anything in your list it will get called. It works like that: Main::yell calls the yell method which checks if the object in list is not null and it isn't. So it calls Main.createIssue. That is why your Main.createIssue is called.

Hope it helps.

2 Answers

Michael Macdonald
Michael Macdonald
34,265 Points

Hey, you were close...but you forgot to add a supplier, or a lambda as Craig did ~ Your requiredNonNull perimeters is this:

Objects.requireNonNull(word, "Created issue" + Main.createIssue());

But, it should be this:

Objects.requireNonNull(word, () -> "Created issue" + Main.createIssue());

Hope this helps ~

J llama
J llama
12,631 Points

what a horrible video