├── README.md ├── predefined-date-formatters.PNG └── src └── com └── ramesh └── java8 ├── GreetingService.java ├── LambdaExamples.java ├── classes ├── CollectorsClassExample.java ├── ForEachMethodExample.java ├── OptionalClassExamples.java └── StringJoinerClassExample.java ├── datetime ├── CompareTwoDatesInJava8.java ├── ConvertStringToLocalDate.java ├── DateTimeDemo.java ├── FlightZoneDateTimeExample.java ├── Java8DateUtility.java ├── LocalDateFormat.java ├── LocalDateTimeFormat.java ├── README.md ├── TimeZoneId.java ├── UseDuration.java ├── UseLocalDate.java ├── UseLocalDateTime.java ├── UseLocalTime.java ├── UsePeriod.java ├── UseToInstant.java └── UseZonedDateTime.java ├── defaultstaticinterfacemethods ├── DefaultInterface.java ├── TestJava8Interface.java ├── impl │ ├── Car.java │ ├── Motorbike.java │ └── MultiAlarmCar.java └── interfaces │ ├── Alarm.java │ └── Vehicle.java ├── functionalInterfaces ├── BiConsumersExample.java ├── BiFunctionExample.java ├── ConsumersExample.java ├── FunctionExample.java ├── FunctionalInterfacesExample.java ├── Person.java ├── PredicateExample.java └── SuppliersExample.java ├── lambda ├── JLEComparatorExample.java ├── JLEExampleMultipleParameters.java ├── JLEExampleMultipleStatements.java ├── JLEExampleNoParameter.java ├── JLEExampleRunnable.java ├── JLEExampleSingleParameter.java ├── JLEExampleWithORWithOutReturnKeyword.java ├── LambdaEventListenerExample.java └── LambdaExpressionExample.java ├── methodreferences ├── ReferenceToConstructor.java ├── ReferenceToInstanceMethod.java ├── ReferenceToStaticMethod.java └── ReferenceToStaticMethod2.java └── streamAPI ├── ConvertListToMap.java ├── ConvertListToSet.java ├── FilteringAndIteratingCollection.java ├── FindMaxAndMinMethods.java ├── JavaStreamExample.java ├── MethodReferenceInStream.java ├── Product.java └── SumByUsingCollectorsMethods.java /README.md: -------------------------------------------------------------------------------- 1 |
2 |
3 | This is a complete guide to Java 8 features, enhancements. The examples from this guide are tested on our local development environment. You can simply clone from Github and try to use it in your projects or practice.
4 |

5 | 1. Java 8 Basic Features Guide

6 |
7 |
8 |
9 | 27 |
28 |

29 | 2. Java 8 Date and Time API Guide

30 | 39 |
    40 |
41 |
42 |
43 | 66 |
67 | -------------------------------------------------------------------------------- /predefined-date-formatters.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RameshMF/java-8-tutorial/f1b5f697668bbbe9aa0aa73e0289d55bd4367c42/predefined-date-formatters.PNG -------------------------------------------------------------------------------- /src/com/ramesh/java8/GreetingService.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8; 2 | 3 | /** 4 | * A service that greets you. 5 | */ 6 | public interface GreetingService { 7 | 8 | static String greet() { 9 | return "Hello World!"; 10 | } 11 | 12 | public static void main(String[] args) { 13 | System.out.println(greet()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/LambdaExamples.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | 8 | public class LambdaExamples { 9 | 10 | public static void main(String[] args) { 11 | 12 | List names = Arrays.asList("peter", "anna", "mike", "xenia"); 13 | 14 | /*Collections.sort(names, new Comparator() { 15 | @Override 16 | public int compare(String a, String b) { 17 | return a.compareTo(b); 18 | } 19 | });*/ 20 | 21 | Collections.sort(names, (a, b) -> a.compareTo(b)); 22 | 23 | for(String str : names){ 24 | System.out.println(str); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/classes/CollectorsClassExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.classes; 2 | 3 | public class CollectorsClassExample { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/classes/ForEachMethodExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.classes; 2 | 3 | public class ForEachMethodExample { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/classes/OptionalClassExamples.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.classes; 2 | 3 | import java.util.Optional; 4 | 5 | public class OptionalClassExamples { 6 | 7 | public static void main(String[] args) { 8 | isPresentOptionalAPI(); 9 | createEmptyOptionalObject(); 10 | createEmptyOptionalObjectWithStaticAPI(); 11 | ifPresentOptionalAPI(); 12 | orElseOptionalAPI(); 13 | orElseOptionalAPI(); 14 | orElseGetOptionalAPI(); 15 | orElseThrowOptionalAPI(); 16 | getOptionalAPI(); 17 | } 18 | 19 | // Returns an Optional with the specified present non-null value. 20 | private static void isPresentOptionalAPI() { 21 | Optional opt = Optional.of("Ramesh"); 22 | System.out.println(opt.isPresent()); 23 | } 24 | 25 | // Returns an Optional with the specified present non-null value. 26 | private static void createEmptyOptionalObject() { 27 | Optional empty = Optional.empty(); 28 | System.out.println(empty.isPresent()); 29 | 30 | // Optional object with the static of API: 31 | String name = "Ramesh"; 32 | Optional.of(name); 33 | } 34 | 35 | private static void createEmptyOptionalObjectWithStaticAPI() { 36 | String name = "baeldung"; 37 | Optional.of(name); 38 | } 39 | 40 | // If a value is present, invoke the specified consumer with the value, otherwise do 41 | // nothing. 42 | private static void ifPresentOptionalAPI() { 43 | // The ifPresent API enables us to run some code on the wrapped value if it is 44 | // found to be non-null. 45 | // Before Optional, we would do something like this: 46 | String name = "Ramesh"; 47 | if (name != null) { 48 | System.out.println(name.length()); 49 | } 50 | 51 | Optional opt = Optional.of("Ramesh"); 52 | opt.ifPresent(str -> System.out.println(str.length())); 53 | } 54 | 55 | // If a value is present, invoke the specified consumer with the value, otherwise do 56 | // nothing. 57 | private static void orElseOptionalAPI() { 58 | // With orElse, the wrapped value is returned if it is present and the argument 59 | // given to 60 | // orElse is returned if the wrapped value is absent 61 | String nullName = null; 62 | 63 | // If a value is present, invoke the specified consumer with the value, otherwise 64 | // do nothing. 65 | // 66 | String name = Optional.ofNullable(nullName).orElse("Ramesh"); 67 | System.out.println(name); 68 | } 69 | 70 | // Return the value if present, otherwise invoke other and return the result of that 71 | // invocation. 72 | private static void orElseGetOptionalAPI() { 73 | String nullName = null; 74 | String name = Optional.ofNullable(nullName).orElseGet(() -> "Ramesh"); 75 | System.out.println(name); 76 | } 77 | 78 | // Return the contained value, if present, otherwise throw an exception to be created 79 | // by the provided supplier. 80 | private static void orElseThrowOptionalAPI() { 81 | 82 | // This will throw exception 83 | String nullName = null; 84 | String name = Optional.ofNullable(nullName) 85 | .orElseThrow(IllegalArgumentException::new); 86 | System.out.println(name); 87 | } 88 | 89 | // If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException 90 | private static void getOptionalAPI() { 91 | Optional opt = Optional.of("Ramesh"); 92 | String name = opt.get(); 93 | System.out.println(name); 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/classes/StringJoinerClassExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.classes; 2 | 3 | import java.util.StringJoiner; 4 | 5 | /** 6 | * Java added a new final class StringJoiner in java.util package. It is used to construct 7 | * a sequence of characters separated by a delimiter 8 | * @author RAMESH 9 | * 10 | */ 11 | public class StringJoinerClassExample { 12 | 13 | public static void main(String[] args) { 14 | delimiterDemonstration(); 15 | addingPrefixAndSuffix(); 16 | mergeTwoStringJoiner(); 17 | stringJoinerMethods(); 18 | } 19 | 20 | private static void delimiterDemonstration() { 21 | StringJoiner joinNames = new StringJoiner(","); // passing comma(,) as delimiter 22 | // Adding values to StringJoiner 23 | joinNames.add("Rahul"); 24 | joinNames.add("Raju"); 25 | joinNames.add("Peter"); 26 | joinNames.add("Raheem"); 27 | System.out.println(joinNames); 28 | 29 | joinNames = new StringJoiner("|"); // passing comma(,) as delimiter 30 | 31 | // Adding values to StringJoiner 32 | joinNames.add("Rahul"); 33 | joinNames.add("Raju"); 34 | joinNames.add("Peter"); 35 | joinNames.add("Raheem"); 36 | System.out.println(joinNames); 37 | } 38 | 39 | private static void addingPrefixAndSuffix() { 40 | // passing comma(,) and 41 | // square-brackets as 42 | // delimiter 43 | StringJoiner joinNames = new StringJoiner(",", "[", "]"); 44 | // Adding values to StringJoiner 45 | joinNames.add("Rahul"); 46 | joinNames.add("Raju"); 47 | joinNames.add("Peter"); 48 | joinNames.add("Raheem"); 49 | 50 | System.out.println(joinNames); 51 | } 52 | 53 | private static void mergeTwoStringJoiner(){ 54 | // passing comma(,) and square-brackets as delimiter 55 | StringJoiner joinNames = new StringJoiner(",", "[", "]"); 56 | 57 | // Adding values to StringJoiner 58 | joinNames.add("Rahul"); 59 | joinNames.add("Raju"); 60 | 61 | // Creating StringJoiner with :(colon) delimiter 62 | StringJoiner joinNames2 = new StringJoiner(":", "[", "]"); // passing colon(:) and square-brackets as delimiter 63 | 64 | // Adding values to StringJoiner 65 | joinNames2.add("Peter"); 66 | joinNames2.add("Raheem"); 67 | 68 | // Merging two StringJoiner 69 | StringJoiner merge = joinNames.merge(joinNames2); 70 | System.out.println(merge); 71 | } 72 | 73 | private static void stringJoinerMethods(){ 74 | StringJoiner joinNames = new StringJoiner(","); // passing comma(,) as delimiter 75 | 76 | // Prints nothing because it is empty 77 | System.out.println(joinNames); 78 | 79 | // We can set default empty value. 80 | joinNames.setEmptyValue("It is empty"); 81 | System.out.println(joinNames); 82 | 83 | 84 | // Adding values to StringJoiner 85 | joinNames.add("Rahul"); 86 | joinNames.add("Raju"); 87 | System.out.println(joinNames); 88 | 89 | // Returns length of StringJoiner 90 | int length = joinNames.length(); 91 | System.out.println("Length: "+length); 92 | 93 | // Returns StringJoiner as String type 94 | String str = joinNames.toString(); 95 | System.out.println(str); 96 | 97 | // Now, we can apply String methods on it 98 | char ch = str.charAt(3); 99 | System.out.println("Character at index 3: "+ch); 100 | 101 | // Adding one more element 102 | joinNames.add("Sorabh"); 103 | System.out.println(joinNames); 104 | 105 | // Returns length 106 | int newLength = joinNames.length(); 107 | System.out.println("New Length: "+newLength); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/CompareTwoDatesInJava8.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | // In Java 8, you can use the new isBefore(), isAfter(), isEqual() and compareTo() to compare LocalDate, LocalTime and LocalDateTime. 7 | public class CompareTwoDatesInJava8 { 8 | public static void main(String[] args) { 9 | 10 | DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd"); 11 | LocalDate date1 = LocalDate.of(2009, 12, 31); 12 | LocalDate date2 = LocalDate.of(2010, 01, 31); 13 | 14 | System.out.println("date1 : " + sdf.format(date1)); 15 | System.out.println("date2 : " + sdf.format(date2)); 16 | 17 | System.out.println("Is..."); 18 | if (date1.isAfter(date2)) { 19 | System.out.println("Date1 is after Date2"); 20 | } 21 | 22 | if (date1.isBefore(date2)) { 23 | System.out.println("Date1 is before Date2"); 24 | } 25 | 26 | if (date1.isEqual(date2)) { 27 | System.out.println("Date1 is equal Date2"); 28 | } 29 | 30 | System.out.println("CompareTo..."); 31 | if (date1.compareTo(date2) > 0) { 32 | 33 | System.out.println("Date1 is after Date2"); 34 | 35 | } else if (date1.compareTo(date2) < 0) { 36 | 37 | System.out.println("Date1 is before Date2"); 38 | 39 | } else if (date1.compareTo(date2) == 0) { 40 | 41 | System.out.println("Date1 is equal to Date2"); 42 | 43 | } else { 44 | 45 | System.out.println("How to get here?"); 46 | 47 | } 48 | } 49 | } 50 | 51 | // http://www.mkyong.com/java/how-to-compare-dates-in-java/ -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/ConvertStringToLocalDate.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.format.DateTimeFormatter; 5 | 6 | public class ConvertStringToLocalDate { 7 | 8 | private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy"); 9 | private static final DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("d-MMM-yyyy"); 10 | private static final DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("d/MM/yyyy"); 11 | public static void main(String[] args) { 12 | 13 | System.out.println(formatter.format(LocalDate.parse("16/08/2016", formatter))); 14 | 15 | System.out.println(formatter1.format(LocalDate.parse("16-Aug-2016", formatter1))); 16 | 17 | System.out.println(formatter2.format(LocalDate.parse("16/08/2016", formatter2))); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/DateTimeDemo.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.LocalTime; 6 | import java.time.Month; 7 | import static java.time.temporal.ChronoUnit.YEARS; 8 | 9 | import java.time.DayOfWeek; 10 | import java.time.temporal.TemporalAdjusters; 11 | 12 | import java.time.Duration; 13 | import java.time.Instant; 14 | 15 | public class DateTimeDemo { 16 | public static void main(String[] args) { 17 | 18 | // set the value for the date of birth 19 | LocalDate dateofBirth = LocalDate.of(1986, Month.APRIL, 06); 20 | System.out.println("Customer date of birth is " + dateofBirth); 21 | 22 | // retrieve the customer's age: 23 | LocalDate now = LocalDate.now(); 24 | System.out.println("Customer now is " + dateofBirth.until(now, YEARS) + " years old."); 25 | 26 | // retrieve the system time and system date and time 27 | LocalTime time = LocalTime.now(); 28 | System.out.println(" Time You logged in is " + time); 29 | LocalDateTime dateTime = LocalDateTime.now(); 30 | System.out.println(" Date and time LocalDateTime You logged in is " + dateTime); 31 | 32 | // manipulating the LocalDate class minus-prefixed method 33 | 34 | LocalDate policyStartdate = LocalDate.now().minusYears(4).minusMonths(2).minusDays(17); 35 | System.out.println("Policy Start Date : " + policyStartdate); 36 | 37 | // retrieve the number of installments paid to date 38 | 39 | int noofInstallmentsPaid = ((now.getYear()) - policyStartdate.getYear()); 40 | System.out.println("No of Installments paid is " + noofInstallmentsPaid); 41 | 42 | /// retrieve the policy end date and the policy maturity date: 43 | 44 | LocalDate policyEnddate = policyStartdate.plusYears(23).plusMonths(11).plusDays(21); 45 | System.out.println("Policy End Date : " + policyEnddate); 46 | LocalDate policyMaturedate = policyEnddate.plusDays(1); 47 | System.out.println("Policy Matures on : " + policyMaturedate); 48 | 49 | // code to calculate the closing balance: 50 | int openingBalance = 0; 51 | float premiumAmount = 35000; 52 | System.out.println("Premium Amount :" + premiumAmount); 53 | int monthlyInterest = (24 / 12); 54 | System.out.println("Monthly Interest Paid by company :" + monthlyInterest); 55 | int noofInstallments = 25; 56 | float closingBalance = ((openingBalance + premiumAmount) * noofInstallments); 57 | System.out.println("closingBalance without interest " + closingBalance); 58 | 59 | // code to calculate the interest rate: 60 | 61 | float interestRate = (float) ((Math.pow((noofInstallments / 4), monthlyInterest)) / monthlyInterest) 62 | * (1 + monthlyInterest); 63 | System.out.println("Overall Interest Rate paid for 25 years is " + interestRate); 64 | 65 | // calculate the number of installments paid by the customer at the age 66 | // of 40: 67 | int yearAtForty = (dateofBirth.getYear()) + 40; 68 | System.out.println("Customer will be 40 at " + yearAtForty); 69 | int noOfPremiumAtForty = yearAtForty - (policyStartdate.getYear()); 70 | System.out.println("No of Premium paid by customer at the age of 40 years is " + noOfPremiumAtForty); 71 | 72 | // code to calculate the interest rate paid when the customer is 40 73 | // years old: 74 | float interestAtForty = (float) ((Math.pow((noOfPremiumAtForty / 4), monthlyInterest)) / monthlyInterest) 75 | * (1 + monthlyInterest); 76 | System.out.println("Interest received by customer at the age of 40 is :" + interestAtForty + "%"); 77 | 78 | // code to calculate the maturity amount: 79 | float maturityAmount = interestRate * premiumAmount; 80 | System.out.println("Maturity Amount is " + maturityAmount); 81 | 82 | // code to calculate the interest amount gained: 83 | float interestAmount = maturityAmount - closingBalance; 84 | System.out.println("Interest Amount gained is " + interestAmount); 85 | 86 | // code to calculate the payment date of the previous installment: 87 | LocalDate lastinstallmentsPaidDate = LocalDate.now().minusMonths(2).minusDays(15); 88 | System.out.println("Last Premium paid Date :" + lastinstallmentsPaidDate); 89 | 90 | // code to calculate the next installment date: 91 | LocalDate NextinstallmentDate = lastinstallmentsPaidDate.plusYears(1).withDayOfMonth(5); 92 | System.out.println("Next Premium Date to be paid :" + NextinstallmentDate); 93 | 94 | // code to calculate the due date of the premium payment: 95 | LocalDate dueDateofPremium = NextinstallmentDate.with(TemporalAdjusters.dayOfWeekInMonth(3, DayOfWeek.MONDAY)); 96 | System.out.println("Due date to pay the premium is " + dueDateofPremium); 97 | 98 | // code to calculate the policy's duration: 99 | Duration h = Duration.ofDays(2); 100 | System.out.println("Duration of policy being active is " + h + " Hours"); 101 | 102 | // code to calculate the instant class date and time: 103 | Instant start = Instant.now().minusSeconds(160); 104 | System.out.println("Instant Start" + start); 105 | Instant end = Instant.now().plusSeconds(60).minusNanos(2); 106 | System.out.println("Instant end" + end); 107 | 108 | // code to calculate the time difference by using the duration class: 109 | Duration a = Duration.between(start, end); 110 | System.out.println("Duration of the site being active is " + a + "seconds"); 111 | 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/FlightZoneDateTimeExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.DateTimeException; 4 | import java.time.LocalDateTime; 5 | import java.time.Month; 6 | import java.time.ZoneId; 7 | import java.time.ZonedDateTime; 8 | import java.time.format.DateTimeFormatter; 9 | /* 10 | * This example uses ZonedDateTime to calculate the arrival time of 11 | * a flight that leaves from San Francisco and arrives in Tokyo. 12 | * The flight is 10 hours, 50 minutes long. Formatters are used to 13 | * print the departure and arrival times. 14 | */ 15 | 16 | public class FlightZoneDateTimeExample { 17 | public static void main(String[] args) { 18 | DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a"); 19 | 20 | // Leaving from San Francisco on July 20, 2013, at 7:30 p.m. 21 | LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); 22 | ZoneId leavingZone = ZoneId.of("America/Los_Angeles"); 23 | ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone); 24 | 25 | try { 26 | String out1 = departure.format(format); 27 | System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone); 28 | } catch (DateTimeException exc) { 29 | System.out.printf("%s can't be formatted!%n", departure); 30 | throw exc; 31 | } 32 | 33 | // Flight is 10 hours and 50 minutes, or 650 minutes 34 | ZoneId arrivingZone = ZoneId.of("Asia/Tokyo"); 35 | ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone) 36 | .plusMinutes(650); 37 | 38 | try { 39 | String out2 = arrival.format(format); 40 | System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone); 41 | } catch (DateTimeException exc) { 42 | System.out.printf("%s can't be formatted!%n", arrival); 43 | throw exc; 44 | } 45 | 46 | if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) 47 | System.out.printf(" (%s daylight saving time will be in effect.)%n", 48 | arrivingZone); 49 | else 50 | System.out.printf(" (%s standard time will be in effect.)%n", 51 | arrivingZone); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/Java8DateUtility.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.DayOfWeek; 4 | import java.time.Duration; 5 | import java.time.Instant; 6 | import java.time.LocalDate; 7 | import java.time.LocalDateTime; 8 | import java.time.LocalTime; 9 | import java.time.MonthDay; 10 | import java.time.ZoneId; 11 | import java.time.ZonedDateTime; 12 | import java.time.format.DateTimeFormatter; 13 | import java.time.temporal.ChronoUnit; 14 | import java.time.temporal.TemporalAdjusters; 15 | import java.util.Calendar; 16 | import java.util.Date; 17 | 18 | //https://javarevisited.blogspot.com/2015/03/20-examples-of-date-and-time-api-from-Java8.html 19 | public final class Java8DateUtility { 20 | 21 | public static LocalDate getLocalDateFromClock() { 22 | LocalDate localDate = LocalDate.now(); 23 | System.out.println("Today's Local date : " + localDate); 24 | return localDate; 25 | } 26 | 27 | public static LocalDate getNextDay(LocalDate localDate) { 28 | return localDate.plusDays(1); 29 | } 30 | 31 | public static LocalDate getPreviousDay(LocalDate localDate) { 32 | return localDate.minus(1, ChronoUnit.DAYS); 33 | } 34 | 35 | public static DayOfWeek getDayOfWeek(LocalDate localDate) { 36 | DayOfWeek day = localDate.getDayOfWeek(); 37 | return day; 38 | } 39 | 40 | public static LocalDate getFirstDayOfMonth() { 41 | LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); 42 | return firstDayOfMonth; 43 | } 44 | 45 | public static LocalDateTime getStartOfDay(LocalDate localDate) { 46 | LocalDateTime startofDay = localDate.atStartOfDay(); 47 | return startofDay; 48 | } 49 | 50 | public static void printCurrentDayMonthAndYear() { 51 | LocalDate today = LocalDate.now(); 52 | int year = today.getYear(); 53 | int month = today.getMonthValue(); 54 | int day = today.getDayOfMonth(); 55 | System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day); 56 | } 57 | 58 | public static LocalDate getParticularDate() { 59 | LocalDate dateOfBirth = LocalDate.of(2010, 01, 14); 60 | System.out.println("Your Date of birth is : " + dateOfBirth); 61 | return dateOfBirth; 62 | } 63 | 64 | public static boolean checkDateEquals(LocalDate date, LocalDate today) { 65 | if (date.equals(today)) { 66 | System.out.printf("Today %s and date1 %s are same date %n", today, date); 67 | return true; 68 | } 69 | return false; 70 | } 71 | 72 | public static void recurringDate(LocalDate today) { 73 | LocalDate dateOfBirth = LocalDate.of(2010, 01, 14); 74 | MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth()); 75 | MonthDay currentMonthDay = MonthDay.from(today); 76 | if (currentMonthDay.equals(birthday)) { 77 | System.out.println("Many Many happy returns of the day !!"); 78 | } else { 79 | System.out.println("Sorry, today is not your birthday"); 80 | } 81 | } 82 | 83 | public static LocalTime getCurrentTime() { 84 | LocalTime time = LocalTime.now(); 85 | System.out.println("local time now : " + time); 86 | return time; 87 | } 88 | 89 | public static LocalTime addHoursToTime(int hours) { 90 | LocalTime time = LocalTime.now(); 91 | LocalTime newTime = time.plusHours(hours); // adding two hours 92 | System.out.println("Time after 2 hours : " + newTime); 93 | return newTime; 94 | } 95 | 96 | public static void findDateAfterWeek() { 97 | LocalDate today = LocalDate.now(); 98 | LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); 99 | System.out.println("Today is : " + today); 100 | System.out.println("Date after 1 week : " + nextWeek); 101 | } 102 | 103 | public static ZonedDateTime timeZone(String timeZone) { 104 | ZoneId america = ZoneId.of(timeZone); 105 | LocalDateTime localtDateAndTime = LocalDateTime.now(); 106 | ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america); 107 | System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork); 108 | return dateAndTimeInNewYork; 109 | } 110 | 111 | public static void checkLeafYear() { 112 | LocalDate today = LocalDate.now(); 113 | if (today.isLeapYear()) { 114 | System.out.println("This year is Leap year"); 115 | } else { 116 | System.out.println("2014 is not a Leap year"); 117 | } 118 | } 119 | 120 | public static Instant getTimeStamp() { 121 | Instant timestamp = Instant.now(); 122 | System.out.println("What is value of this instant " + timestamp); 123 | return timestamp; 124 | } 125 | 126 | public static void compareTwoDates(LocalDate date1, LocalDate date2) { 127 | if (date1.compareTo(date2) > 0) { 128 | System.out.println("Date1 is after Date2"); 129 | } else if (date1.compareTo(date2) < 0) { 130 | System.out.println("Date1 is before Date2"); 131 | } 132 | } 133 | 134 | public static LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) { 135 | return LocalTime.of(hour, min, seconds); 136 | } 137 | 138 | public static ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { 139 | return ZonedDateTime.of(localDateTime, zoneId); 140 | } 141 | 142 | // Returns a copy of this time with the specified amount added. 143 | public static LocalTime modifyDates(LocalTime localTime, Duration duration) { 144 | return localTime.plus(duration); 145 | } 146 | 147 | // Obtains a Duration representing the duration between two temporal 148 | // objects. 149 | public static Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) { 150 | return Duration.between(localTime1, localTime2); 151 | } 152 | 153 | public static LocalDateTime getLocalDateTimeUsingParseMethod(String representation) { 154 | return LocalDateTime.parse(representation); 155 | } 156 | 157 | public static LocalDateTime convertDateToLocalDate(Date date) { 158 | return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); 159 | } 160 | 161 | public static LocalDateTime convertDateToLocalDate(Calendar calendar) { 162 | return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()); 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/LocalDateFormat.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalDate; 4 | 5 | import java.time.format.DateTimeFormatter; 6 | 7 | public class LocalDateFormat { 8 | private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy"); 9 | private static final DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("d-MMM-yyyy"); 10 | private static final DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("d/MM/yyyy"); 11 | public static void main(String[] args) { 12 | //default format 13 | System.out.println("Default format of LocalDate = " + LocalDate.now()); 14 | 15 | // The ISO date formatter that formats or parses a date without an 16 | // offset, such as '20111203' 17 | LocalDate date = LocalDate.now(); 18 | 19 | System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE)); 20 | 21 | System.out.println(date.format(DateTimeFormatter.ISO_DATE)); 22 | 23 | System.out.println(formatter.format(LocalDate.parse("16/08/2016", formatter))); 24 | 25 | System.out.println(formatter1.format(LocalDate.parse("16-Aug-2016", formatter1))); 26 | 27 | System.out.println(formatter2.format(LocalDate.parse("16/08/2016", formatter2))); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/LocalDateTimeFormat.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.Instant; 4 | 5 | import java.time.LocalDateTime; 6 | import java.time.format.DateTimeFormatter; 7 | 8 | public class LocalDateTimeFormat { 9 | 10 | public static void main(String[] args) { 11 | 12 | LocalDateTime dateTime = LocalDateTime.now(); 13 | 14 | //default format 15 | System.out.println("Default format of LocalDateTime="+dateTime); 16 | 17 | //specific format 18 | System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"))); 19 | 20 | System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE)); 21 | 22 | Instant timestamp = Instant.now(); 23 | 24 | //default format 25 | System.out.println("Default format of Instant="+timestamp); 26 | 27 | //Parse examples 28 | LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48", 29 | DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")); 30 | System.out.println("Default format after parsing = "+dt); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/README.md: -------------------------------------------------------------------------------- 1 | ### Relevant Articles: 2 | - [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) 3 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/TimeZoneId.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.IOException; 5 | import java.nio.charset.StandardCharsets; 6 | import java.nio.file.Files; 7 | import java.nio.file.Path; 8 | import java.nio.file.Paths; 9 | import java.time.LocalDateTime; 10 | import java.time.ZoneId; 11 | import java.time.ZoneOffset; 12 | import java.time.ZonedDateTime; 13 | import java.util.ArrayList; 14 | import java.util.Collections; 15 | import java.util.List; 16 | import java.util.Set; 17 | 18 | public class TimeZoneId { 19 | public static void main(String[] args) { 20 | 21 | // Get the set of all time zone IDs. 22 | Set allZones = ZoneId.getAvailableZoneIds(); 23 | 24 | // Create a List using the set of zones and sort it. 25 | List zoneList = new ArrayList(allZones); 26 | Collections.sort(zoneList); 27 | 28 | LocalDateTime dt = LocalDateTime.now(); 29 | 30 | Path p = Paths.get("timeZones"); 31 | try (BufferedWriter tzfile = Files.newBufferedWriter(p, StandardCharsets.US_ASCII)) { 32 | for (String s : zoneList) { 33 | ZoneId zone = ZoneId.of(s); 34 | ZonedDateTime zdt = dt.atZone(zone); 35 | ZoneOffset offset = zdt.getOffset(); 36 | int secondsOfHour = offset.getTotalSeconds() % (60 * 60); 37 | String out = String.format("%35s %10s%n", zone, offset); 38 | 39 | // Write only time zones that do not have a whole hour offset 40 | // to standard out. 41 | if (secondsOfHour != 0) { 42 | System.out.printf(out); 43 | } 44 | 45 | // Write all time zones to the file. 46 | tzfile.write(out); 47 | } 48 | } catch (IOException x) { 49 | System.err.format("IOException: %s%n", x); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/UseDuration.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.Duration; 4 | import java.time.LocalTime; 5 | 6 | public class UseDuration { 7 | 8 | public LocalTime modifyDates(LocalTime localTime, Duration duration) { 9 | return localTime.plus(duration); 10 | } 11 | 12 | public Duration getDifferenceBetweenDates(LocalTime localTime1, LocalTime localTime2) { 13 | return Duration.between(localTime1, localTime2); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/UseLocalDate.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.DayOfWeek; 4 | import java.time.LocalDate; 5 | import java.time.LocalDateTime; 6 | import java.time.temporal.ChronoUnit; 7 | import java.time.temporal.TemporalAdjusters; 8 | 9 | class UseLocalDate { 10 | 11 | LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) { 12 | return LocalDate.of(year, month, dayOfMonth); 13 | } 14 | 15 | LocalDate getLocalDateUsingParseMethod(String representation) { 16 | return LocalDate.parse(representation); 17 | } 18 | 19 | LocalDate getLocalDateFromClock() { 20 | LocalDate localDate = LocalDate.now(); 21 | return localDate; 22 | } 23 | 24 | LocalDate getNextDay(LocalDate localDate) { 25 | return localDate.plusDays(1); 26 | } 27 | 28 | LocalDate getPreviousDay(LocalDate localDate) { 29 | return localDate.minus(1, ChronoUnit.DAYS); 30 | } 31 | 32 | DayOfWeek getDayOfWeek(LocalDate localDate) { 33 | DayOfWeek day = localDate.getDayOfWeek(); 34 | return day; 35 | } 36 | 37 | LocalDate getFirstDayOfMonth() { 38 | LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); 39 | return firstDayOfMonth; 40 | } 41 | 42 | LocalDateTime getStartOfDay(LocalDate localDate) { 43 | LocalDateTime startofDay = localDate.atStartOfDay(); 44 | return startofDay; 45 | } 46 | 47 | public static void main(String[] args) { 48 | UseLocalDate localDate = new UseLocalDate(); 49 | System.out.println(localDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10) 50 | .toString()); 51 | System.out.println(localDate.getLocalDateUsingParseMethod("2016-05-10") 52 | .toString()); 53 | System.out.println(localDate.getLocalDateFromClock()); 54 | System.out.println(localDate.getNextDay(localDate.getLocalDateFromClock())); 55 | System.out.println(localDate.getPreviousDay(localDate.getLocalDateFromClock())); 56 | System.out.println(localDate.getDayOfWeek(localDate.getLocalDateFromClock())); 57 | System.out.println(localDate.getFirstDayOfMonth()); 58 | System.out.println(localDate.getStartOfDay(localDate.getLocalDateFromClock())); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/UseLocalDateTime.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public class UseLocalDateTime { 6 | 7 | public LocalDateTime getLocalDateTimeUsingParseMethod(String representation) { 8 | return LocalDateTime.parse(representation); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/UseLocalTime.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalTime; 4 | import java.time.temporal.ChronoUnit; 5 | 6 | public class UseLocalTime { 7 | 8 | LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) { 9 | return LocalTime.of(hour, min, seconds); 10 | } 11 | 12 | LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { 13 | return LocalTime.parse(timeRepresentation); 14 | } 15 | 16 | //Obtains the current time from the system clock in the default time-zone. 17 | private LocalTime getLocalTimeFromClock() { 18 | return LocalTime.now(); 19 | } 20 | 21 | // Returns a copy of this time with the specified amount added. 22 | LocalTime addAnHour(LocalTime localTime) { 23 | return localTime.plus(1, ChronoUnit.HOURS); 24 | } 25 | 26 | int getHourFromLocalTime(LocalTime localTime) { 27 | return localTime.getHour(); 28 | } 29 | 30 | LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) { 31 | return localTime.withMinute(minute); 32 | } 33 | 34 | public static void main(String[] args) { 35 | UseLocalTime localTime = new UseLocalTime(); 36 | 37 | System.out.println("Current local time : " + localTime.getLocalTimeFromClock()); 38 | System.out.println(" LocalTime representing 08:30 AM \t: " + localTime.getLocalTimeUsingParseMethod("08:30")); 39 | System.out.println("add an hour to current time : " + localTime.addAnHour(LocalTime.of(11, 11))); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/UsePeriod.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.Period; 5 | 6 | class UsePeriod { 7 | 8 | LocalDate modifyDates(LocalDate localDate, Period period) { 9 | return localDate.plus(period); 10 | } 11 | 12 | Period getDifferenceBetweenDates(LocalDate localDate1, LocalDate localDate2) { 13 | return Period.between(localDate1, localDate2); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/UseToInstant.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.ZoneId; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | 8 | public class UseToInstant { 9 | 10 | public LocalDateTime convertDateToLocalDate(Date date) { 11 | return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); 12 | } 13 | 14 | public LocalDateTime convertDateToLocalDate(Calendar calendar) { 15 | return LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/datetime/UseZonedDateTime.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.datetime; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.ZoneId; 5 | import java.time.ZonedDateTime; 6 | 7 | class UseZonedDateTime { 8 | 9 | ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { 10 | return ZonedDateTime.of(localDateTime, zoneId); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/defaultstaticinterfacemethods/DefaultInterface.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.interfaces; 2 | 3 | /* 4 | * Copyright (c) 2008,2012 Oracle and/or its affiliates. All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * - Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 13 | * - Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * 17 | * - Neither the name of Oracle or the names of its 18 | * contributors may be used to endorse or promote products derived 19 | * from this software without specific prior written permission. 20 | * 21 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 22 | * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 23 | * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 24 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 25 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 26 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 27 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 28 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 29 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 30 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 31 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | */ 33 | 34 | // CharSequenceDemo presents a String value -- backwards. 35 | public class DefaultInterface implements CharSequence { 36 | private String s; 37 | 38 | public DefaultInterface(String s) { 39 | //It would be much more efficient to just reverse the string 40 | //in the constructor. But a lot less fun! 41 | this.s = s; 42 | } 43 | 44 | //If the string is backwards, the end is the beginning! 45 | private int fromEnd(int i) { 46 | return s.length() - 1 - i; 47 | } 48 | 49 | public char charAt(int i) { 50 | if ((i < 0) || (i >= s.length())) { 51 | throw new StringIndexOutOfBoundsException(i); 52 | } 53 | return s.charAt(fromEnd(i)); 54 | } 55 | 56 | public int length() { 57 | return s.length(); 58 | } 59 | 60 | public CharSequence subSequence(int start, int end) { 61 | if (start < 0) { 62 | throw new StringIndexOutOfBoundsException(start); 63 | } 64 | if (end > s.length()) { 65 | throw new StringIndexOutOfBoundsException(end); 66 | } 67 | if (start > end) { 68 | throw new StringIndexOutOfBoundsException(start - end); 69 | } 70 | StringBuilder sub = 71 | new StringBuilder(s.subSequence(fromEnd(end), fromEnd(start))); 72 | return sub.reverse(); 73 | } 74 | 75 | public String toString() { 76 | StringBuilder s = new StringBuilder(this.s); 77 | return s.reverse().toString(); 78 | } 79 | 80 | //Random int from 0 to max. As random() generates values between 0 and 0.9999 81 | private static int random(int max) { 82 | return (int) Math.round(Math.random() * (max+1)); 83 | } 84 | 85 | public static void main(String[] args) { 86 | DefaultInterface s = 87 | new DefaultInterface("Write a class that implements the CharSequence interface found in the java.lang package."); 88 | 89 | //exercise charAt() and length() 90 | for (int i = 0; i < s.length(); i++) { 91 | System.out.print(s.charAt(i)); 92 | } 93 | 94 | System.out.println(""); 95 | 96 | //exercise subSequence() and length(); 97 | int start = random(s.length() - 1); 98 | int end = random(s.length() - 1 - start) + start; 99 | System.out.println(s.subSequence(start, end)); 100 | 101 | //exercise toString(); 102 | System.out.println(s); 103 | 104 | } 105 | } -------------------------------------------------------------------------------- /src/com/ramesh/java8/defaultstaticinterfacemethods/TestJava8Interface.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.defaultstaticinterfacemethods; 2 | 3 | import com.ramesh.java8.defaultstaticinterfacemethods.impl.Car; 4 | import com.ramesh.java8.defaultstaticinterfacemethods.impl.Motorbike; 5 | import com.ramesh.java8.defaultstaticinterfacemethods.impl.MultiAlarmCar; 6 | import com.ramesh.java8.defaultstaticinterfacemethods.interfaces.Vehicle; 7 | 8 | public class TestJava8Interface { 9 | public static void main(String[] args) { 10 | 11 | Vehicle car = new Car("BMW"); 12 | System.out.println(car.getBrand()); 13 | System.out.println(car.speedUp()); 14 | System.out.println(car.slowDown()); 15 | System.out.println(car.turnAlarmOn()); 16 | System.out.println(car.turnAlarmOff()); 17 | System.out.println(Vehicle.getHorsePower(2500, 480)); 18 | 19 | Vehicle bike = new Motorbike("ACTIVA 4G"); 20 | System.out.println(bike.getBrand()); 21 | System.out.println(bike.speedUp()); 22 | System.out.println(bike.slowDown()); 23 | System.out.println(bike.turnAlarmOn()); 24 | System.out.println(bike.turnAlarmOff()); 25 | System.out.println(Vehicle.getHorsePower(2500, 480)); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/defaultstaticinterfacemethods/impl/Car.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.defaultstaticinterfacemethods.impl; 2 | 3 | import com.ramesh.java8.defaultstaticinterfacemethods.interfaces.Vehicle; 4 | 5 | public class Car implements Vehicle { 6 | 7 | private final String brand; 8 | 9 | public Car(String brand) { 10 | this.brand = brand; 11 | } 12 | 13 | @Override 14 | public String getBrand() { 15 | return brand; 16 | } 17 | 18 | @Override 19 | public String speedUp() { 20 | return "The car is speeding up."; 21 | } 22 | 23 | @Override 24 | public String slowDown() { 25 | return "The car is slowing down."; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/defaultstaticinterfacemethods/impl/Motorbike.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.defaultstaticinterfacemethods.impl; 2 | 3 | import com.ramesh.java8.defaultstaticinterfacemethods.interfaces.Vehicle; 4 | 5 | public class Motorbike implements Vehicle { 6 | 7 | private final String brand; 8 | 9 | public Motorbike(String brand) { 10 | this.brand = brand; 11 | } 12 | 13 | @Override 14 | public String getBrand() { 15 | return brand; 16 | } 17 | 18 | @Override 19 | public String speedUp() { 20 | return "The motorbike is speeding up."; 21 | } 22 | 23 | @Override 24 | public String slowDown() { 25 | return "The motorbike is slowing down."; 26 | } 27 | } -------------------------------------------------------------------------------- /src/com/ramesh/java8/defaultstaticinterfacemethods/impl/MultiAlarmCar.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.defaultstaticinterfacemethods.impl; 2 | 3 | import com.ramesh.java8.defaultstaticinterfacemethods.interfaces.Alarm; 4 | import com.ramesh.java8.defaultstaticinterfacemethods.interfaces.Vehicle; 5 | 6 | public class MultiAlarmCar implements Vehicle, Alarm { 7 | 8 | private final String brand; 9 | 10 | public MultiAlarmCar(String brand) { 11 | this.brand = brand; 12 | } 13 | 14 | @Override 15 | public String getBrand() { 16 | return brand; 17 | } 18 | 19 | @Override 20 | public String speedUp() { 21 | return "The motorbike is speeding up."; 22 | } 23 | 24 | @Override 25 | public String slowDown() { 26 | return "The mootorbike is slowing down."; 27 | } 28 | 29 | @Override 30 | public String turnAlarmOn() { 31 | return Vehicle.super.turnAlarmOn() + " " + Alarm.super.turnAlarmOn(); 32 | } 33 | 34 | @Override 35 | public String turnAlarmOff() { 36 | return Vehicle.super.turnAlarmOff() + " " + Alarm.super.turnAlarmOff(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/defaultstaticinterfacemethods/interfaces/Alarm.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.defaultstaticinterfacemethods.interfaces; 2 | 3 | public interface Alarm { 4 | default String turnAlarmOn() { 5 | return "Turning the alarm on."; 6 | } 7 | 8 | default String turnAlarmOff() { 9 | return "Turning the alarm off."; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/defaultstaticinterfacemethods/interfaces/Vehicle.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.defaultstaticinterfacemethods.interfaces; 2 | 3 | public interface Vehicle { 4 | String getBrand(); 5 | 6 | String speedUp(); 7 | 8 | String slowDown(); 9 | 10 | default String turnAlarmOn() { 11 | return "Turning the vehice alarm on."; 12 | } 13 | 14 | default String turnAlarmOff() { 15 | return "Turning the vehicle alarm off."; 16 | } 17 | 18 | static int getHorsePower(int rpm, int torque) { 19 | return (rpm * torque) / 5252; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/functionalInterfaces/BiConsumersExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.functionalInterfaces; 2 | 3 | import java.util.function.BiConsumer; 4 | 5 | public class BiConsumersExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | BiConsumer biConsumer = (p1, p2) -> { 10 | System.out.println(" print first persion"); 11 | System.out.println(p1.getName()); 12 | System.out.println(" print second persion"); 13 | System.out.println(p2.getName()); 14 | }; 15 | 16 | biConsumer.accept(new Person("Ramesh", 10), new Person("ram", 10)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/functionalInterfaces/BiFunctionExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.functionalInterfaces; 2 | 3 | import java.util.function.BiFunction; 4 | 5 | public class BiFunctionExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | BiFunction biFunction = (p1,p2) -> { 10 | return p1.getAge() + p2.getAge(); 11 | }; 12 | 13 | int totalAge = biFunction.apply(new Person("Ramesh", 10), new Person("ram", 10)); 14 | System.out.println(totalAge); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/functionalInterfaces/ConsumersExample.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RameshMF/java-8-tutorial/f1b5f697668bbbe9aa0aa73e0289d55bd4367c42/src/com/ramesh/java8/functionalInterfaces/ConsumersExample.java -------------------------------------------------------------------------------- /src/com/ramesh/java8/functionalInterfaces/FunctionExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.functionalInterfaces; 2 | 3 | import java.util.function.Function; 4 | 5 | // A Function is a functional interface whose sole purpose is to return any result by working on a single input argument. 6 | //It represents a function that accepts one argument and returns a result. 7 | public class FunctionExample { 8 | 9 | public static void main(String[] args) { 10 | // convert centigrade to fahrenheit 11 | Function centigradeToFahrenheitInt = x -> new Double((x*9/5)+32); 12 | System.out.println("Centigrade to Fahrenheit: "+centigradeToFahrenheitInt.apply(100)); 13 | 14 | // String to an integer 15 | Function stringToInt = x -> Integer.valueOf(x); 16 | System.out.println(" String to Int: " + stringToInt.apply("4")); 17 | 18 | 19 | Function function = (entity) -> { 20 | return new PersonDTO(entity.getName(), entity.getAge()); 21 | }; 22 | PersonDTO personDTO = function.apply(new PersonEntity("ramesh", 20)); 23 | System.out.println(personDTO.getName()); 24 | System.out.println(personDTO.getAge()); 25 | } 26 | } 27 | 28 | class PersonEntity { 29 | private String name; 30 | private int age; 31 | 32 | public PersonEntity(String name, int age) { 33 | super(); 34 | this.name = name; 35 | this.age = age; 36 | } 37 | 38 | public String getName() { 39 | return name; 40 | } 41 | 42 | public void setName(String name) { 43 | this.name = name; 44 | } 45 | 46 | public int getAge() { 47 | return age; 48 | } 49 | 50 | public void setAge(int age) { 51 | this.age = age; 52 | } 53 | } 54 | 55 | class PersonDTO { 56 | private String name; 57 | private int age; 58 | 59 | public PersonDTO(String name, int age) { 60 | super(); 61 | this.name = name; 62 | this.age = age; 63 | } 64 | 65 | public String getName() { 66 | return name; 67 | } 68 | 69 | public void setName(String name) { 70 | this.name = name; 71 | } 72 | 73 | public int getAge() { 74 | return age; 75 | } 76 | 77 | public void setAge(int age) { 78 | this.age = age; 79 | } 80 | } -------------------------------------------------------------------------------- /src/com/ramesh/java8/functionalInterfaces/FunctionalInterfacesExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.functionalInterfaces; 2 | 3 | 4 | // An Interface that contains exactly one abstract method is known as functional interface 5 | // It can have any number of default, static methods but can contain only one abstract method. It can also declare methods of object class. 6 | // It is a new feature in Java, which helps to achieve functional programming approach. 7 | // The Java API has many one-method interfaces such as Runnable, Callable, Comparator, ActionListener and others. They can be implemented and instantiated using anonymous class syntax. 8 | 9 | 10 | // Rules 11 | // A functional interface can extends another interface only when it does not have any abstract method. 12 | 13 | public class FunctionalInterfacesExample { 14 | 15 | public static void main(String[] args) { 16 | 17 | Sayable sayable = (msg) -> { 18 | System.out.println(msg); 19 | }; 20 | sayable.say("Say something .."); 21 | } 22 | } 23 | 24 | @FunctionalInterface 25 | interface Sayable{ 26 | void say(String msg); // abstract method 27 | // It can contain any number of Object class methods. 28 | int hashCode(); 29 | String toString(); 30 | boolean equals(Object obj); 31 | } 32 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/functionalInterfaces/Person.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.functionalInterfaces; 2 | 3 | public class Person { 4 | private String name; 5 | private int age; 6 | 7 | public Person(String name, int age) { 8 | super(); 9 | this.name = name; 10 | this.age = age; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public int getAge() { 22 | return age; 23 | } 24 | 25 | public void setAge(int age) { 26 | this.age = age; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/functionalInterfaces/PredicateExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.functionalInterfaces; 2 | 3 | import java.util.function.Predicate; 4 | 5 | // We need a function for checking a condition. A Predicate is one such function accepting a single argument to evaluate to a boolean result. 6 | // It has a single method test which returns the boolean value. 7 | public class PredicateExample { 8 | 9 | public static void main(String[] args) { 10 | 11 | Predicate predicate = (person) -> person.getAge() > 28; 12 | boolean result = predicate.test(new Person("ramesh", 29)); 13 | System.out.println(result); 14 | } 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/functionalInterfaces/SuppliersExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.functionalInterfaces; 2 | 3 | import java.util.function.Supplier; 4 | 5 | public class SuppliersExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | Supplier supplier = () -> { 10 | return new Person("Ramesh", 30 ); 11 | }; 12 | 13 | Person p = supplier.get(); 14 | System.out.println("Person Detail:\n" + p.getName() + ", " + p.getAge()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/JLEComparatorExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | 8 | public class JLEComparatorExample { 9 | 10 | public static void main(String[] args) { 11 | 12 | List listOfPerson = new ArrayList(); 13 | listOfPerson.add(new Person("abc", 27)); 14 | listOfPerson.add(new Person("mno", 26)); 15 | listOfPerson.add(new Person("pqr", 28)); 16 | listOfPerson.add(new Person("xyz", 27)); 17 | 18 | // Without lambda expression. 19 | // Sort list by age 20 | Comparator comparator = new Comparator() { 21 | @Override 22 | public int compare(Person o1, Person o2) { 23 | return o1.getAge() - o2.getAge(); 24 | } 25 | }; 26 | 27 | Collections.sort(listOfPerson, comparator); 28 | 29 | System.out.println(" sort persons by age in ascending order"); 30 | for (Person person : listOfPerson) { 31 | System.out.println(" Person name : " + person.getName()); 32 | } 33 | 34 | // Witht lambda expression. 35 | // Sort list by age 36 | 37 | Collections.sort(listOfPerson, (Person o1, Person o2) -> { 38 | return o1.getAge() - o2.getAge(); 39 | }); 40 | // Use forEach method added in java 8 41 | System.out.println(" sort persons by age in ascending order"); 42 | listOfPerson.forEach( 43 | (person) -> System.out.println(" Person name : " + person.getName())); 44 | } 45 | } 46 | 47 | class Person { 48 | private String name; 49 | private int age; 50 | 51 | public Person(String name, int age) { 52 | super(); 53 | this.name = name; 54 | this.age = age; 55 | } 56 | 57 | public String getName() { 58 | return name; 59 | } 60 | 61 | public void setName(String name) { 62 | this.name = name; 63 | } 64 | 65 | public int getAge() { 66 | return age; 67 | } 68 | 69 | public void setAge(int age) { 70 | this.age = age; 71 | } 72 | } -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/JLEExampleMultipleParameters.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | interface Addable{ 4 | int add(int a,int b); 5 | } 6 | public class JLEExampleMultipleParameters { 7 | 8 | public static void main(String[] args) { 9 | 10 | // without lambda expression 11 | Addable addable = new Addable() { 12 | @Override 13 | public int add(int a, int b) { 14 | return a + b; 15 | } 16 | }; 17 | addable.add(10, 20); 18 | 19 | // with lambda expression 20 | // Multiple parameters in lambda expression 21 | Addable withLambda = (a,b)->(a+b); 22 | System.out.println(withLambda.add(10,20)); 23 | 24 | // Multiple parameters with data type in lambda expression 25 | Addable withLambdaD = (int a,int b) -> (a+b); 26 | System.out.println(withLambdaD.add(100,200)); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/JLEExampleMultipleStatements.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | interface IAvarage{ 4 | double avg(int[] array); 5 | } 6 | public class JLEExampleMultipleStatements { 7 | 8 | public static void main(String[] args) { 9 | 10 | // without lambda expression, IAvarage implementation using anonymous class 11 | IAvarage avarage = new IAvarage() { 12 | @Override 13 | public double avg(int[] array) { 14 | double sum = 0; 15 | int arraySize = array.length; 16 | 17 | System.out.println("arraySize : " + arraySize); 18 | for (int i = 0; i < array.length; i++) { 19 | sum = sum + array[i]; 20 | } 21 | System.out.println("sum : " + sum); 22 | 23 | return (sum/ arraySize); 24 | } 25 | }; 26 | int[] array = {1,4,6,8,9}; 27 | System.out.println(avarage.avg(array)); 28 | 29 | // with lambda expression 30 | // You can pass multiple statements in lambda expression 31 | 32 | IAvarage withLambda = (withLambdaArray) -> { 33 | double sum = 0; 34 | int arraySize = withLambdaArray.length; 35 | 36 | System.out.println("arraySize : " + arraySize); 37 | for (int i = 0; i < withLambdaArray.length; i++) { 38 | sum = sum + withLambdaArray[i]; 39 | } 40 | System.out.println("sum : " + sum); 41 | 42 | return (sum/ arraySize); 43 | }; 44 | 45 | int[] withLambdaArray = {1,4,6,8,9}; 46 | System.out.println(withLambda.avg(withLambdaArray)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/JLEExampleNoParameter.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | interface Sayable { 4 | public String say(); 5 | } 6 | public class JLEExampleNoParameter { 7 | public static void main(String[] args) { 8 | // without lambda expression 9 | Sayable sayable = new Sayable() { 10 | @Override 11 | public String say() { 12 | return "Return something .."; 13 | } 14 | }; 15 | sayable.say(); 16 | 17 | // with lambda expression 18 | Sayable withLambda = () -> { 19 | return "Return something .."; 20 | }; 21 | withLambda.say(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/JLEExampleRunnable.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | public class JLEExampleRunnable { 4 | 5 | public static void main(String[] args) { 6 | 7 | //without lambda, Runnable implementation using anonymous class 8 | Runnable runnable = new Runnable() { 9 | @Override 10 | public void run() { 11 | System.out.println(" Runnable example without lambda exp."); 12 | } 13 | }; 14 | Thread thread = new Thread(runnable); 15 | thread.run(); 16 | 17 | //with lambda 18 | Runnable withLambda = () -> System.out.println(" Runnable example with lambda exp."); 19 | withLambda.run(); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/JLEExampleSingleParameter.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | interface Printable{ 4 | 5 | void print(String msg); 6 | } 7 | 8 | public class JLEExampleSingleParameter { 9 | 10 | public static void main(String[] args) { 11 | 12 | // without lambda expression 13 | 14 | Printable printable = new Printable() { 15 | @Override 16 | public void print(String msg) { 17 | System.out.println(msg); 18 | } 19 | }; 20 | printable.print(" Print message to console...."); 21 | 22 | // with lambda expression 23 | Printable withLambda = (msg) -> System.out.println(msg); 24 | withLambda.print(" Print message to console...."); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/JLEExampleWithORWithOutReturnKeyword.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | interface Arithmatic { 4 | int add(int a, int b); 5 | } 6 | 7 | /** 8 | * In Java lambda expression, if there is only one statement, you may or may not use return keyword. You must use return keyword when lambda expression contains multiple statements. 9 | * @author RAMESH 10 | * 11 | */ 12 | public class JLEExampleWithORWithOutReturnKeyword { 13 | 14 | public static void main(String[] args) { 15 | 16 | // without lambda expression 17 | Arithmatic addable = new Arithmatic() { 18 | @Override 19 | public int add(int a, int b) { 20 | return a + b; 21 | } 22 | }; 23 | addable.add(10, 20); 24 | 25 | // Lambda expression without return keyword. 26 | Arithmatic withLambda = (a, b) -> (a + b); 27 | System.out.println(withLambda.add(10, 20)); 28 | 29 | // Lambda expression with return keyword. 30 | Arithmatic arithmatic = (int a, int b) -> { 31 | return (a + b); 32 | }; 33 | System.out.println(arithmatic.add(100, 200)); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/LambdaEventListenerExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | import javax.swing.JButton; 4 | import javax.swing.JFrame; 5 | import javax.swing.JTextField; 6 | public class LambdaEventListenerExample { 7 | public static void main(String[] args) { 8 | JTextField tf=new JTextField(); 9 | tf.setBounds(50, 50,150,20); 10 | JButton b=new JButton("click"); 11 | b.setBounds(80,100,70,30); 12 | // lambda expression implementing here. 13 | b.addActionListener(e-> {tf.setText("hello swing");}); 14 | JFrame f=new JFrame(); 15 | f.add(tf);f.add(b); 16 | f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 17 | f.setLayout(null); 18 | f.setSize(300, 200); 19 | f.setVisible(true); 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/lambda/LambdaExpressionExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.lambda; 2 | 3 | interface Drawable{ 4 | public void draw(); 5 | } 6 | public class LambdaExpressionExample { 7 | public static void main(String[] args) { 8 | int width=10; 9 | 10 | //without lambda, Drawable implementation using anonymous class 11 | Drawable withoutLambda =new Drawable(){ 12 | public void draw(){System.out.println("Drawing "+width);} 13 | }; 14 | withoutLambda.draw(); 15 | 16 | //with lambda 17 | Drawable withLambda=()->{ 18 | System.out.println("Drawing "+width); 19 | }; 20 | withLambda.draw(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/methodreferences/ReferenceToConstructor.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.methodreferences; 2 | 3 | // Syntex : ClassName::new 4 | 5 | //You can refer a constructor by using the new keyword. Here, we are referring constructor with the help of functional interface. 6 | public class ReferenceToConstructor { 7 | public static void main(String[] args) { 8 | Messageable hello = Message::new; 9 | hello.getMessage("Hello"); 10 | } 11 | } 12 | 13 | interface Messageable{ 14 | Message getMessage(String msg); 15 | } 16 | 17 | class Message{ 18 | Message(String msg){ 19 | System.out.print(msg); 20 | } 21 | } -------------------------------------------------------------------------------- /src/com/ramesh/java8/methodreferences/ReferenceToInstanceMethod.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.methodreferences; 2 | 3 | // Syntex : containingObject::instanceMethodName 4 | public class ReferenceToInstanceMethod { 5 | 6 | public void saySomething() { 7 | System.out.println("Hello, this is non-static method."); 8 | } 9 | 10 | public static void main(String[] args) { 11 | // Creating object 12 | ReferenceToInstanceMethod methodReference = new ReferenceToInstanceMethod(); 13 | // Referring non-static method using reference 14 | Sayable sayable = methodReference::saySomething; 15 | // Calling interface method 16 | sayable.say(); 17 | // Referring non-static method using anonymous object 18 | 19 | // You can use anonymous object also 20 | Sayable sayable2 = new ReferenceToInstanceMethod()::saySomething; 21 | // Calling interface method 22 | sayable2.say(); 23 | } 24 | } 25 | 26 | interface Sayable { 27 | void say(); 28 | } -------------------------------------------------------------------------------- /src/com/ramesh/java8/methodreferences/ReferenceToStaticMethod.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.methodreferences; 2 | 3 | public class ReferenceToStaticMethod { 4 | 5 | // Syntex : ContainingClass::staticMethodName 6 | public static void main(String[] args) { 7 | 8 | // Using lambda expression 9 | Thread thread = new Thread(() -> System.out.println("Thread is running using lambda...")); 10 | thread.start(); 11 | 12 | // using predefined functional interface Runnable to refer static method 13 | Thread t2 = new Thread(ReferenceToStaticMethod::ThreadStatus); 14 | t2.start(); 15 | } 16 | 17 | public static void ThreadStatus() { 18 | System.out.println("Thread is running..."); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/methodreferences/ReferenceToStaticMethod2.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.methodreferences; 2 | 3 | import java.util.function.BiFunction; 4 | 5 | class Arithmetic { 6 | public static int add(int a, int b) { 7 | return a + b; 8 | } 9 | 10 | public static float add(int a, float b) { 11 | return a + b; 12 | } 13 | 14 | public static float add(float a, float b) { 15 | return a + b; 16 | } 17 | } 18 | 19 | public class ReferenceToStaticMethod2 { 20 | public static void main(String[] args) { 21 | BiFunction adder1 = Arithmetic::add; 22 | BiFunction adder2 = Arithmetic::add; 23 | BiFunction adder3 = Arithmetic::add; 24 | int result1 = adder1.apply(10, 20); 25 | float result2 = adder2.apply(10, 20.0f); 26 | float result3 = adder3.apply(10.0f, 20.0f); 27 | System.out.println(result1); 28 | System.out.println(result2); 29 | System.out.println(result3); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/streamAPI/ConvertListToMap.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.streamAPI; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.stream.Collectors; 7 | 8 | public class ConvertListToMap { 9 | public static void main(String[] args) { 10 | List productsList = new ArrayList(); 11 | 12 | // Adding Products 13 | productsList.add(new Product(1, "HP Laptop", 25000f)); 14 | productsList.add(new Product(2, "Dell Laptop", 30000f)); 15 | productsList.add(new Product(3, "Lenevo Laptop", 28000f)); 16 | productsList.add(new Product(4, "Sony Laptop", 28000f)); 17 | productsList.add(new Product(5, "Apple Laptop", 90000f)); 18 | 19 | // Converting Product List into a Map 20 | Map productPriceMap = productsList.stream() 21 | .collect(Collectors.toMap(p -> p.getId(), p -> p.getName())); 22 | System.out.println(productPriceMap); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/streamAPI/ConvertListToSet.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.streamAPI; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Set; 6 | import java.util.stream.Collectors; 7 | 8 | public class ConvertListToSet { 9 | public static void main(String[] args) { 10 | List productsList = new ArrayList(); 11 | 12 | // Adding Products 13 | productsList.add(new Product(1, "HP Laptop", 25000f)); 14 | productsList.add(new Product(2, "Dell Laptop", 30000f)); 15 | productsList.add(new Product(3, "Lenevo Laptop", 28000f)); 16 | productsList.add(new Product(4, "Sony Laptop", 28000f)); 17 | productsList.add(new Product(5, "Apple Laptop", 90000f)); 18 | 19 | // Converting product List into Set 20 | Set productPriceList = productsList.stream() 21 | .filter(product -> product.getPrice() < 30000) 22 | .map(product -> product.getPrice()).collect(Collectors.toSet()); 23 | System.out.println(productPriceList); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/streamAPI/FilteringAndIteratingCollection.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.streamAPI; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class FilteringAndIteratingCollection { 7 | public static void main(String[] args) { 8 | List productsList = new ArrayList(); 9 | // Adding Products 10 | productsList.add(new Product(1, "HP Laptop", 25000f)); 11 | productsList.add(new Product(2, "Dell Laptop", 30000f)); 12 | productsList.add(new Product(3, "Lenevo Laptop", 28000f)); 13 | productsList.add(new Product(4, "Sony Laptop", 28000f)); 14 | productsList.add(new Product(5, "Apple Laptop", 90000f)); 15 | // This is more compact approach for filtering data 16 | productsList.stream().filter(product -> product.getPrice() == 30000) 17 | .forEach(product -> System.out.println(product.getPrice())); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/streamAPI/FindMaxAndMinMethods.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.streamAPI; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class FindMaxAndMinMethods { 7 | public static void main(String[] args) { 8 | List productsList = new ArrayList(); 9 | // Adding Products 10 | productsList.add(new Product(1, "HP Laptop", 25000f)); 11 | productsList.add(new Product(2, "Dell Laptop", 30000f)); 12 | productsList.add(new Product(3, "Lenevo Laptop", 28000f)); 13 | productsList.add(new Product(4, "Sony Laptop", 28000f)); 14 | productsList.add(new Product(5, "Apple Laptop", 90000f)); 15 | // max() method to get max Product price 16 | Product productA = productsList 17 | .stream().max((product1, 18 | product2) -> product1.getPrice() > product2.getPrice() ? 1 : -1) 19 | .get(); 20 | 21 | System.out.println(productA.getPrice()); 22 | // min() method to get min Product price 23 | Product productB = productsList 24 | .stream().max((product1, 25 | product2) -> product1.getPrice() < product2.getPrice() ? 1 : -1) 26 | .get(); 27 | System.out.println(productB.getPrice()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/streamAPI/JavaStreamExample.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.streamAPI; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class JavaStreamExample { 8 | private static List productsList = new ArrayList(); 9 | 10 | public static void main(String[] args) { 11 | 12 | // Adding Products 13 | productsList.add(new Product(1, "HP Laptop", 25000f)); 14 | productsList.add(new Product(2, "Dell Laptop", 30000f)); 15 | productsList.add(new Product(3, "Lenevo Laptop", 28000f)); 16 | productsList.add(new Product(4, "Sony Laptop", 28000f)); 17 | productsList.add(new Product(5, "Apple Laptop", 90000f)); 18 | // Without Java 8 Stream API'S 19 | withoutStreamAPI(); 20 | // With Java 8 Stream API'S 21 | withStreamAPI(); 22 | } 23 | 24 | private static void withoutStreamAPI() { 25 | // without Stream API's 26 | List productPriceList = new ArrayList(); 27 | // filtering data of list 28 | for (Product product : productsList) { 29 | if (product.getPrice() > 25000) { 30 | // adding price to a productPriceList 31 | productPriceList.add(product.getPrice()); 32 | } 33 | } 34 | 35 | // displaying data 36 | for (Float price : productPriceList) { 37 | System.out.println(price); 38 | } 39 | } 40 | 41 | private static void withStreamAPI() { 42 | // filtering data of list 43 | List productPriceList = productsList.stream() 44 | .filter((product) -> product.getPrice() > 25000) 45 | .map((product) -> product.getPrice()).collect(Collectors.toList()); 46 | // displaying data 47 | productPriceList.forEach((price) -> System.out.println(price)); 48 | } 49 | } -------------------------------------------------------------------------------- /src/com/ramesh/java8/streamAPI/MethodReferenceInStream.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.streamAPI; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class MethodReferenceInStream { 8 | public static void main(String[] args) { 9 | 10 | List productsList = new ArrayList(); 11 | 12 | // Adding Products 13 | productsList.add(new Product(1, "HP Laptop", 25000f)); 14 | productsList.add(new Product(2, "Dell Laptop", 30000f)); 15 | productsList.add(new Product(3, "Lenevo Laptop", 28000f)); 16 | productsList.add(new Product(4, "Sony Laptop", 28000f)); 17 | productsList.add(new Product(5, "Apple Laptop", 90000f)); 18 | 19 | List productPriceList = productsList.stream() 20 | .filter(p -> p.getPrice() > 30000)// filtering data 21 | .map(Product::getPrice) // fetching price by referring getPrice method 22 | .collect(Collectors.toList()); // collecting as list 23 | System.out.println(productPriceList); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/streamAPI/Product.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.streamAPI; 2 | 3 | public class Product { 4 | private int id; 5 | private String name; 6 | private float price; 7 | public Product(int id, String name, float price) { 8 | this.id = id; 9 | this.name = name; 10 | this.price = price; 11 | } 12 | public int getId() { 13 | return id; 14 | } 15 | public void setId(int id) { 16 | this.id = id; 17 | } 18 | public String getName() { 19 | return name; 20 | } 21 | public void setName(String name) { 22 | this.name = name; 23 | } 24 | public float getPrice() { 25 | return price; 26 | } 27 | public void setPrice(float price) { 28 | this.price = price; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/ramesh/java8/streamAPI/SumByUsingCollectorsMethods.java: -------------------------------------------------------------------------------- 1 | package com.ramesh.java8.streamAPI; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class SumByUsingCollectorsMethods { 8 | public static void main(String[] args) { 9 | List productsList = new ArrayList(); 10 | //Adding Products 11 | productsList.add(new Product(1,"HP Laptop",25000f)); 12 | productsList.add(new Product(2,"Dell Laptop",30000f)); 13 | productsList.add(new Product(3,"Lenevo Laptop",28000f)); 14 | productsList.add(new Product(4,"Sony Laptop",28000f)); 15 | productsList.add(new Product(5,"Apple Laptop",90000f)); 16 | // Using Collectors's method to sum the prices. 17 | double totalPrice3 = productsList.stream() 18 | .collect(Collectors.summingDouble(product->product.getPrice())); 19 | System.out.println(totalPrice3); 20 | 21 | } 22 | } 23 | --------------------------------------------------------------------------------