A series of Java tips and examples, hope you like it.
Classic
- How to sort a Map in Java
- How to detect OS in Java
- Java – How to display all System properties
- Java Properties file examples
- How to get the environment variables in Java
- Java 7 try-with-resources example
- Java Scanner examples
- How to change the JVM default locale?
Logging
- SLF4J Logback Tutorial
- logback.xml Examples
- Logback – different log file for each thread
- Logback – Set log file name programmatically
- Logback – Disable logging in Unit Test
- Logback – Duplicate log messages
- How to stop logback status INFO at the start of every log?
- Log4j Tutorial
- log4j.xml Examples
- log4j.properties examples
- Apache Log4j 2 Tutorials
- log4j2.properties example
- log4j2.yml example
Java 8
FAQs
Some common asked questions.
- Java 8 forEach examples
- Java 8 Convert List to Map
- Java 8 Lambda : Comparator example
- Java 8 method references, double colon (::) operator
- Java 8 Streams filter examples
- Java 8 Streams map() examples
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 |
- Java 8 Function examples
- Java 8 BiFunction examples
- Java 8 BinaryOperator examples
- Java 8 UnaryOperator Examples
- Java 8 Predicate examples
- Java 8 BiPredicate examples
- Java 8 Consumer examples
- Java 8 BiConsumer examples
- Java 8 Supplier Examples
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
- Java 8 Streams filter examples
- Java 8 Streams map() examples
- Java 8 flatMap example
- Java 8 Parallel Streams Examples
- Java 8 Stream.iterate examples
- Java 8 Stream Collectors groupingBy examples
- Java 8 Filter a null value from a Stream
- Java 8 Convert a Stream to List
- Java 8 Stream findFirst() and findAny()
- Java 8 Stream.reduce() examples
- Java 8 Convert a Stream to List
- Java 8 How to Sum BigDecimal using Stream?
- Java 8 Stream – Read a file line by line
- Java 8 Stream – Convert List<List<String>> to List<String>
- Java 8 Stream – The peek() is not working with count()?
- Java 8 Should we close the Stream after use?
- Java 8 Convert a Stream to Array
- Java 8 How to convert IntStream to Integer array
- Java 8 How to convert IntStream to int or int array
- Java 8 How to sort list with stream.sorted()
- Java – How to sum all the stream integers
- Java – How to convert a primitive Array to List
- How to convert Array to List in Java
- Java – How to convert Array to Stream
- Java – Stream has already been operated upon or closed
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…
- Java – How to get current date time
- Java – How to get current timestamp
- Java – How to convert String to a Date
- Java 8 – Duration and Period examples
- Java 8 – How to convert String to LocalDate
- Java 8 – How to format LocalDateTime
- Java 8 – Convert Instant to LocalDateTime
- Java 8 – Convert Instant to ZoneDateTime
- Java 8 – Convert Date to LocalDate and LocalDateTime
- Java 8 – ZonedDateTime examples
- Java – Convert date and time between timezone
- Java – How to add days to current date
- Java 8 – TemporalAdjusters examples
- Java 8 – Convert Epoch time milliseconds to LocalDate or LocalDateTime
- Java 8 – Difference between two LocalDate or LocalDateTime
- Java 8 – How to calculate days between two dates?
- Java 8 – How to parse date with “dd MMM” (02 Jan), without year?
- Java 8 – Convert LocalDate and LocalDateTime to Date
- Java 8 – Unable to obtain LocalDateTime from TemporalAccessor
- Java 8 – How to parse date with LocalDateTime
- Java 8 – Convert ZonedDateTime to Timestamp
- Java – Display all ZoneId and its UTC offset
- Java – Display list of TimeZone with GMT
- Java 8 – Convert LocalDateTime to Timestamp
- Java – How to change date format in a String
- Java – Check if the date is older than 6 months
- Java – How to compare dates
- Java – How to calculate elapsed time
- Java 8 – MinguoDate examples (Taiwan calendar)
- Java 8 – HijrahDate, How to calculate the Ramadan date (Islamic calendar)
- Java Date and Calendar examples
- Java Date Time Tutorials
5. Java 8 Tips
- Java 8 Optional In Depth
- Java 8 How to sort a Map
- Java 8 Convert List to Map
- Java 8 Filter a Map examples
- Java 8 Convert Map to List
- Java 8 StringJoiner example
- Java 8 Math Exact examples
- Java 8 forEach print with Index
- Java 8 Convert Optional<String> to String
- Java – How to print a Pyramid
- Java – Check if Array contains a certain value?
- Java – How to declare and initialize an Array
- Java – How to join Arrays
- How to print an Array in Java
- How to copy an Array in Java
- How to sort an Array in java
- Java – Generate random integers in a range
- Java – How to print a name 10 times?
- Java – How to search a string in a List?
- Java – How to get keys and values from Map
- Java – Convert File to String
- Java – Convert Array to ArrayList
- Java – How to check if a String is numeric
- Java – How to join List String with commas
- Java – Convert comma-separated String to a List
- Java Prime Numbers examples
- How to tell Maven to use Java 8
- java.lang.UnsupportedClassVersionError
- Java Fibonacci examples
- How to loop a Map in Java
- Java Regular Expression Examples
- How to read file in Java – BufferedReader
- How to calculate monetary values in Java
- Java – Display double in 2 decimal places
- Java – How to round double / float value to 2 decimal places
- How to format a double in Java
- Java – Convert String to double
Java 17
JAR Working
- How to make a Java exe file or executable JAR file
- How to add a manifest into a Jar file
- The Java Archive Tool (JAR) Examples
Installation
- How to install Oracle JDK 8 on CentOS
- How to Install Oracle JDK 8 On Debian
- How to install Java on Mac OS
- How to Set JAVA_HOME environment variable on macOS
- How to install Java JDK on Ubuntu
- How to check JDK version that installed on your computer
- How to add JAVA_HOME on Ubuntu?
- How to set JAVA_HOME on Windows 10?