Main Tutorials

Java 8 Tutorials

java 8 logo

A series of Java 8 tips and examples, hope you like it.

FAQs

Some common asked questions.

1. Functional Interface

Java 8 introduced @FunctionalInterface, an interface that has exactly one abstract method. The compiler will treat any interfaces meeting the definition of a functional interface as a functional interface; it means the @FunctionalInterface annotation is optional.

Let us see the six basic function interfaces.

Interface Signature Examples
UnaryOperator<T> T apply(T t) String::toLowerCase, Math::tan
BinaryOperator<T> T apply(T t1, T t2) BigInteger::add, Math::pow
Function<T, R> R apply(T t) Arrays::asList, Integer::toBinaryString
Predicate<T, U> boolean test(T t, U u) String::isEmpty, Character::isDigit
Supplier<T> T get() LocalDate::now, Instant::now
Consumer<T> void accept(T t) System.out::println, Error::printStackTrace

2. Lambda Expressions & Method References

Java 8 introduced lambda expressions to provide the implementation of the abstract method of a functional interface.

Further Reading >>> Java 8 Lambda : Comparator example

Review the JDK Iterable class, it has a default method forEach() to accept a function interface Consumer

Iterable.java

public interface Iterable<T> {

    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

   //...
}

First, we can provide an anonymous class as the forEach implementation.


List<String> list = Arrays.asList("node", "java", "python", "ruby");
list.forEach(new Consumer<String>() {       // anonymous class
    @Override
    public void accept(String str) {
        System.out.println(str);
    }
});

Alternatively, we can use a lambda expression to shorten the code like this:


List<String> list = Arrays.asList("node", "java", "python", "ruby");
list.forEach(str -> System.out.println(str)); // lambda expressions

To gain better readability, we can replace lambda expression with method reference.


List<String> list = Arrays.asList("node", "java", "python", "ruby");
list.forEach(System.out::println);           // method references

Further Reading >>> Java 8 method references, double colon (::) operator

Note
Both lambda expression or method reference does nothing but just another way call to an existing method. With method reference, it gains better readability.

3. Streams

4. New Date Time APIs

In the old days, we use Date and Calendar APIs to represent and manipulate date.

  • java.util.Date – date and time, print with default time-zone.
  • java.util.Calendar – date and time, more methods to manipulate date.
  • java.text.SimpleDateFormat – formatting (date -> text), parsing (text -> date) for date and calendar.

Java 8 created a series of new date and time APIs in java.time package. (JSR310 and inspired by Joda-time).

  • java.time.LocalDate – date without time, no time-zone.
  • java.time.LocalTime – time without date, no time-zone.
  • java.time.LocalDateTime – date and time, no time-zone.
  • java.time.ZonedDateTime – date and time, with time-zone.
  • java.time.DateTimeFormatter – formatting (date -> text), parsing (text -> date) for java.time.
  • java.time.Instant – date and time for machine, seconds passed since the Unix epoch time (midnight of January 1, 1970 UTC)
  • java.time.Duration – Measures time in seconds and nanoseconds.
  • java.time.Period – Measures time in years, months and days.
  • java.time.TemporalAdjuster – Adjust date.
  • java.time.OffsetDateTime – {update me}

Examples…

5. Java 8 Tips

Installation

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
36 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mrinmoy Dey
6 years ago

From last 5 years,I am referring Mkyong.com whenever I need help. Thanks..

Bimal Parajuli
4 years ago

I have been referring to this website for a long time ago. I like the way information is shared on this website. The explanation of the requirement and scenario is very clearly documented. The font-size, color combination, text format and wrapper of the code is eye-catching. I would use this website because it has a clear explanation of the topic and solution. It has good examples written in pretty understandable, easy and simple language.
Usually, I don’t write the review for any of the websites that I follow but this website has helped me a lot on solving my project issues, providing me the best way to solve the problem. I am really impressed by its content. I am always getting clear technical understanding from this website. I want to thank a lot to the owner of this website for making this technical website and sharing a bunch of useful information. I am pretty sure a lot of beginners and intermediate level developers or students will be referencing this website to gain useful and valuable knowledge. I really think this is a great platform to learn and share information to and from this site. Once again a big thank you to the owner Mkyong for designing such a wonderful website and providing valuable knowledge.

Eric YANG
3 years ago
Reply to  Bimal Parajuli

Yes, the website explains the technical issues with an easy and simple example, you can catch the points very fast. I also reference the website for a long time. Thanks very much for Mr. MKYONG’s contribution. thanks again

ram
3 years ago
Reply to  mkyong

Hi Sir, Do you offer training.

Ngoc Khuong
6 years ago

Thank you :)))

don k4sperski
6 years ago

Excellent java 8 resources

Tu Hoa Tri
4 years ago

May be you lack of “match” method…

hamidreza
1 year ago

I need to thank you for your useful and categorized information to help transfer the right knowledge

Hossam Elbadissi
3 years ago

I love the way you love what you do and how you do it exceptionally well. Keep it up!

prem
4 years ago

One of the most important features of lambdas is behind the scenes it supports optimisation using invokedynamic. Also the streams api does very well when used in parallel mode on multi cpu, multi core machines. I found more about that here
https://stackrules.com/learn-java-8-streams-api-in-an-hour/

duliu
6 years ago

Good

Matthew
9 months ago

The best website for Java. The examples and the references listed are what I need to learn the new feature since Java 8. My simple words can’t express my appreciation to Mkyong.

mangata
2 years ago

thanks to your article, it helps me a lot

tao
2 years ago

It would be nice to have an example under the concurrent package

sky07
3 years ago

thanks

liam
3 years ago

Hi..I am new to Java but your material seems very well structured and I find it very good..Thank you

I will look at the mentioned charities

Liam

anmol
3 years ago

awesome resource

garca1826
3 years ago

Mkyong.com is one of my masters in java

Cong
4 years ago

thank you 😀 😀 😀

Neha Jain
4 years ago

A very trustworthy study resource. Thanks a ton!

bvds
4 years ago

Great!

Daniel Melero
4 years ago

Thanks, you are the man!

adam
4 years ago

Great explanations , do you offer training ?

srini
4 years ago

where is the definition for Developer.java?

Kondalarao
5 years ago

Nice examples.. Thank you

Madhu
5 years ago

Very good java 8 resource.

sathyamurthy
5 years ago

Hi
Thank you so much and please provide source code too.
Sathya

Smithb636
5 years ago

hi!,I love your writing so much! share we communicate more approximately your post on AOL? I need an expert in this space to resolve my problem. Maybe that’s you! Looking forward to peer you. kabackkckkebkbce

zako
5 years ago
Reply to  Smithb636

Nice tutorial !

Anirban Chatterjee
6 years ago

StackOverflow and MkYoung you are next to Oracle(Sun) when it is about Java 🙂

yahoo
4 years ago

hgh

lucas
6 years ago

can’t say anything for article. tks so much. love u

arasu
6 years ago

try to add all methods in java8 otherwise super.