├── .gitignore └── src └── com └── modernjava ├── datetime ├── ConvertToLocalDateTime.java ├── ConvertToZonedDateTimeExample.java ├── DateModifyExample.java ├── DateTimeExample.java ├── DurationExample.java ├── InstantExample.java ├── LocalDateExample.java ├── LocalDateTimeExample.java ├── LocalDateTimeToDateAndTimeExample.java ├── LocalTimeExample.java ├── LocalTimeModifyExample.java └── ZoneExample.java ├── defaults ├── Calculator.java ├── DefaultsStaticExample.java ├── InterfaceA.java ├── InterfaceB.java ├── InterfaceC.java ├── InterfaceD.java ├── MathOperationsExample.java ├── MultipleIneritanceExample.java └── MultipleInheritanceDebuggingExample.java ├── factorymethods └── FactoryMethodsExample.java ├── funcprogramming ├── BiConsumerExample.java ├── BiConsumerExample2.java ├── BiFunctionExample.java ├── BiPredicateExample.java ├── BinaryOperatorExample.java ├── ConstructorReferenceExample.java ├── ConsumerExample.java ├── ConsumerExample2.java ├── ConsumerExample3.java ├── ConvertToMethodReferenceExample.java ├── FunctionExample.java ├── FunctionExample2.java ├── Instructor.java ├── InstructorFactory.java ├── Instructors.java ├── MethodReferenceExample.java ├── PredicateAndBiConsumerExample.java ├── PredicateExample.java ├── PredicateExample2.java ├── PredicateExample3.java ├── SupplierExample.java ├── Test.java ├── UnaryOperatorExample.java ├── VariableScope.java └── realexample │ ├── AccountFactory.java │ ├── BankAccount.java │ └── BankTransfer.java ├── java9improvements ├── MultiLineTextBlockExample.java ├── SafeArgsExample.java ├── SwitchExpressionEnhancementExample.java ├── SwitchExpressionExample2.java ├── SwitchExpressionsExample1.java ├── SwitchStatementExample.java └── TryWithResourcesExample.java ├── javaimprovements ├── AsyncHttpClient.java ├── HttpClientExample.java ├── TypeInterferenceExample.java └── VarWithLambdaExample.java ├── lambda ├── ComparatorExample.java ├── ConcatenateInterface.java ├── ConcetanateTraditional.java ├── ConcetenateLambda.java ├── HelloWorldInterface.java ├── HelloWorldLambda.java ├── HelloWorldTraditional.java ├── IncrementByFiveInterface.java ├── IncrementByFiveLambda.java ├── IncrementByFiveTraditional.java ├── RunnableExample.java └── SumOfNumbersUsingCallable.java ├── optional ├── OptionalExample.java ├── OptionalIfIsExample.java ├── OptionalOfEmptyExample.java └── OptionalOrElseThrowExample.java ├── parallelstream ├── ParallelStreamExample.java ├── StreamPerformanceExample.java └── StreamPerformanceExample1.java └── streams ├── BoxingUnBoxingExample.java ├── CollectorMappingExample.java ├── CollectorSummingAveragingExample.java ├── CollectorsMinMaxExample.java ├── CountingExample.java ├── DoubleStreamExample.java ├── FilterExample.java ├── FlatMapExample.java ├── GroupingByExample1.java ├── GroupingExample2.java ├── GroupingExample3.java ├── GroupingMinMaxAvgExample.java ├── IntStreamExample.java ├── JoiningExample.java ├── LongStreamExample.java ├── MapExample.java ├── MapToObjLongDoubleExample.java ├── NumericStreamAggregateExample.java ├── PartitioningByExample.java ├── StreamComparatorExample.java ├── StreamExample.java ├── StreamFactoryMethodExample.java ├── StreamFindAnyAndFirstExample.java ├── StreamLimitAndSkipExample.java ├── StreamMapFilterReduceExample.java ├── StreamMaxExample.java ├── StreamMinExample.java ├── StreamReduceExample.java ├── StreamReduceExample2.java ├── StreamVsCollectionExample.java └── StreamsOperations.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Java template 3 | # Compiled class file 4 | *.class 5 | 6 | # Log file 7 | *.log 8 | 9 | # BlueJ files 10 | *.ctxt 11 | 12 | # Mobile Tools for Java (J2ME) 13 | .mtj.tmp/ 14 | 15 | # Package Files # 16 | *.jar 17 | *.war 18 | *.nar 19 | *.ear 20 | *.zip 21 | *.tar.gz 22 | *.rar 23 | 24 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 25 | hs_err_pid* 26 | 27 | 28 | .idea 29 | *.iml 30 | *.kotlin_module 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/ConvertToLocalDateTime.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.ZoneId; 6 | import java.util.Date; 7 | 8 | public class ConvertToLocalDateTime { 9 | public static void main(String[] args) { 10 | Date date = new Date(); 11 | LocalDateTime localDateTime = date.toInstant(). 12 | atZone(ZoneId.systemDefault()).toLocalDateTime(); 13 | System.out.println("localDateTime = " + localDateTime); 14 | 15 | java.sql.Date dateSql = new java.sql.Date(System.currentTimeMillis()); 16 | LocalDate localDate = dateSql.toLocalDate(); 17 | System.out.println("localDate = " + localDate); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/ConvertToZonedDateTimeExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.ZoneId; 5 | import java.time.ZoneOffset; 6 | import java.time.ZonedDateTime; 7 | 8 | public class ConvertToZonedDateTimeExample { 9 | public static void main(String[] args) { 10 | LocalDateTime localDateTime = LocalDateTime.now(); 11 | System.out.println("localDateTime = " + localDateTime); 12 | ZonedDateTime zonedDateTime = localDateTime. 13 | atZone(ZoneId.of("America/New_York")); 14 | System.out.println("zonedDateTime = " + zonedDateTime); 15 | System.out.println(localDateTime.atOffset(ZoneOffset.ofHours(-10))); 16 | 17 | } 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/DateModifyExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.temporal.ChronoField; 5 | import java.time.temporal.TemporalAdjusters; 6 | 7 | public class DateModifyExample { 8 | public static void main(String[] args) { 9 | LocalDate localDate = LocalDate.now(); 10 | //4 days from now 11 | localDate= localDate.plusDays(4); 12 | System.out.println("localDate = " + localDate); 13 | System.out.println("localDate.plusDays(4) = " + localDate.plusDays(4)); 14 | localDate = localDate.now(); 15 | System.out.println("localDate = " + localDate); 16 | System.out.println("localDate.plusMonths(2) = " + localDate.plusMonths(2)); 17 | System.out.println("localDate.plusYears(2) = " + localDate.plusYears(2)); 18 | System.out.println("localDate.minusDays(10) = " + localDate.minusDays(10)); 19 | System.out.println("localDate.withYear(2023) = " + localDate.withYear(2023)); 20 | // 21 | System.out.println("localDate.with(ChronoField) = " 22 | + localDate.with(ChronoField.YEAR, 2025)); 23 | 24 | System.out.println("localDate.with(TemporalAdjusters) = " 25 | + localDate.with(TemporalAdjusters.lastDayOfMonth())); 26 | 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/DateTimeExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.text.DateFormat; 4 | import java.text.SimpleDateFormat; 5 | import java.time.LocalDate; 6 | import java.time.LocalDateTime; 7 | import java.time.LocalTime; 8 | import java.util.Calendar; 9 | import java.util.Date; 10 | 11 | public class DateTimeExample { 12 | public static void main(String[] args) { 13 | //Date and simpledateformatter 14 | Date dateObj = new Date(); 15 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 16 | System.out.println("df.format(dateObj) = " + df.format(dateObj)); 17 | 18 | df = new SimpleDateFormat("HH:mm:ss"); 19 | System.out.println("df.format(dateObj) = " + df.format(dateObj)); 20 | 21 | System.out.println(Calendar.getInstance().getTime()); 22 | 23 | //LocalDate 24 | LocalDate localDate = LocalDate.now(); 25 | System.out.println("localDate = " + localDate); 26 | //LocalTime 27 | LocalTime localTime = LocalTime.now(); 28 | System.out.println("localTime = " + localTime); 29 | //LocalDateTime 30 | LocalDateTime localDateTime = LocalDateTime.now(); 31 | System.out.println("localDateTime = " + localDateTime); 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/DurationExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.Duration; 4 | import java.time.LocalDate; 5 | import java.time.LocalDateTime; 6 | import java.time.LocalTime; 7 | 8 | public class DurationExample { 9 | public static void main(String[] args) { 10 | //duration between 2 localdatetime instances 11 | LocalDateTime localDateTime = LocalDateTime.now(); 12 | LocalDateTime localDateTime1 = LocalDateTime.now().plusHours(2); 13 | Duration duration = Duration.between(localDateTime, localDateTime1); 14 | System.out.println("duration.toHours() = " + duration.toHours()); 15 | 16 | duration = Duration.ofHours(3); 17 | System.out.println("duration.toMinutes() = " + duration.toMinutes()); 18 | 19 | LocalTime localTime = LocalTime.now(); 20 | LocalTime localTime1 = LocalTime.now().plusMinutes(60); 21 | duration = Duration.between(localTime, localTime1); 22 | System.out.println("duration = " + duration.toMinutes()); 23 | 24 | LocalDate localDate = LocalDate.now(); 25 | LocalDate localDate1 = LocalDate.now().plusDays(1); 26 | duration = Duration.between(localDate, localDate1); 27 | System.out.println("duration = " + duration); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/InstantExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.*; 4 | 5 | public class InstantExample { 6 | public static void main(String[] args) { 7 | Instant timestamp = Instant.now(); 8 | System.out.println("timestamp.getNano() = " + timestamp.getNano()); 9 | 10 | Instant timestamp1 = Instant.now().plusSeconds(3600); 11 | Duration duration = Duration.between(timestamp1,timestamp); 12 | System.out.println("duration.toSeconds() = " + duration.toSeconds()); 13 | 14 | LocalDateTime ld = LocalDateTime.ofInstant(timestamp1, ZoneId.systemDefault()); 15 | System.out.println("ld = " + ld); 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/LocalDateExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.temporal.ChronoField; 5 | 6 | public class LocalDateExample { 7 | public static void main(String[] args) { 8 | //creating localdate 9 | LocalDate localDate = LocalDate.now(); 10 | System.out.println("localDate = " + localDate); 11 | 12 | //using day of the year 13 | localDate = LocalDate.ofYearDay(2018, 35); 14 | System.out.println("localDate = " + localDate); 15 | 16 | // 17 | localDate = LocalDate.of(2018, 05, 23); 18 | System.out.println("localDate = " + localDate); 19 | 20 | localDate = LocalDate.now(); 21 | 22 | //Get Methods 23 | System.out.println("localDate.getMonth = " + localDate.getMonth()); 24 | System.out.println("localDate.getMonthValue() = " + localDate.getMonthValue()); 25 | System.out.println("localDate.getDayOfWeek() = " + localDate.getDayOfWeek()); 26 | System.out.println("localDate.getD = " + localDate.getDayOfYear()); 27 | System.out.println("localDate = " + localDate.get(ChronoField.MONTH_OF_YEAR)); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/LocalDateTimeExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.LocalTime; 6 | import java.time.temporal.ChronoField; 7 | 8 | public class LocalDateTimeExample { 9 | public static void main(String[] args) { 10 | LocalDateTime localDateTime = LocalDateTime.now(); 11 | System.out.println("localDateTime = " + localDateTime); 12 | 13 | //of 14 | localDateTime = LocalDateTime.of(2022, 1, 12, 12,12,12); 15 | System.out.println("localDateTime = " + localDateTime); 16 | 17 | localDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.now()); 18 | System.out.println("localDateTime = " + localDateTime); 19 | 20 | //get 21 | System.out.println("localDateTime.getHour() = " + localDateTime.getHour()); 22 | System.out.println("localDateTime.getMonth() = " + localDateTime.getMonth()); 23 | System.out.println("localDateTime.getMinute() = " + localDateTime.getMinute()); 24 | System.out.println("localDateTime.getSecond() = " + localDateTime.getSecond()); 25 | System.out.println("localDateTime.get() = " 26 | + localDateTime.get(ChronoField.MONTH_OF_YEAR)); 27 | 28 | //Modify 29 | System.out.println("localDateTime.plusYears(3) = " + localDateTime.plusYears(3)); 30 | System.out.println("localDateTime.plusHours(4) = " + localDateTime.plusHours(4)); 31 | System.out.println("localDateTime.plusMinutes(60) = " + localDateTime.plusMinutes(60)); 32 | System.out.println("localDateTime.with(ChronoField) = " 33 | + localDateTime.with(ChronoField.HOUR_OF_DAY,3)); 34 | System.out.println("localDateTime.with(LocalTime) = " 35 | + localDateTime.with(LocalTime.MIDNIGHT)); 36 | 37 | 38 | 39 | 40 | 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/LocalDateTimeToDateAndTimeExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.LocalDate; 4 | import java.time.LocalDateTime; 5 | import java.time.LocalTime; 6 | 7 | public class LocalDateTimeToDateAndTimeExample { 8 | public static void main(String[] args) { 9 | LocalDateTime localDateTime = LocalDateTime.now(); 10 | System.out.println("localDateTime.toLocalDate() = " + localDateTime.toLocalDate()); 11 | System.out.println("localDateTime.toLocalTime() = " + localDateTime.toLocalTime()); 12 | 13 | localDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.now()); 14 | System.out.println("localDateTime = " + localDateTime); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/LocalTimeExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.LocalTime; 4 | import java.time.temporal.ChronoField; 5 | 6 | public class LocalTimeExample { 7 | public static void main(String[] args) { 8 | LocalTime localTime = LocalTime.now(); 9 | System.out.println("localTime = " + localTime); 10 | 11 | localTime = LocalTime.of (15, 18); 12 | System.out.println("localTime = " + localTime); 13 | 14 | localTime = LocalTime.of(15, 18, 22); 15 | System.out.println("localTime = " + localTime); 16 | 17 | localTime = LocalTime.of(15,18,23,22222222); 18 | System.out.println("localTime = " + localTime); 19 | 20 | //get 21 | System.out.println("localTime.getHour() = " + localTime.getHour()); 22 | System.out.println("localTime.getMinute() = " + localTime.getMinute()); 23 | System.out.println("localTime.getSecond() = " + localTime.getSecond()); 24 | System.out.println("localTime.getNano() = " + localTime.getNano()); 25 | 26 | System.out.println("localTime.get(ChronoField) = " 27 | + localTime.get(ChronoField.SECOND_OF_DAY)); 28 | System.out.println("localTime.get(ChronoField) = " + 29 | localTime.get(ChronoField.MINUTE_OF_DAY)); 30 | 31 | 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/LocalTimeModifyExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.LocalTime; 4 | import java.time.temporal.ChronoField; 5 | import java.time.temporal.ChronoUnit; 6 | 7 | public class LocalTimeModifyExample { 8 | public static void main(String[] args) { 9 | LocalTime localTime = LocalTime.now();; 10 | System.out.println("localTime.plusHours(2) = " + localTime.plusHours(2)); 11 | System.out.println("localTime.plusMinutes(22) = " + localTime.plusMinutes(22)); 12 | System.out.println("localTime.plusSeconds(30) = " + localTime.plusSeconds(30)); 13 | System.out.println("localTime.plusNanos(222222) = " + localTime.plusNanos(222222)); 14 | System.out.println("localTime.minusHours(2) = " + localTime.minusHours(2)); 15 | System.out.println("localTime.minus(ChroUnit.) = " 16 | + localTime.minus(2, ChronoUnit.HOURS)); 17 | 18 | System.out.println("localTime.with(LocalTime.MIDNIGHT) = " 19 | + localTime.with(LocalTime.MIDNIGHT)); 20 | System.out.println("localTime.with(ChronoField) = " 21 | + localTime.with(ChronoField.HOUR_OF_DAY,4)); 22 | 23 | 24 | 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/modernjava/datetime/ZoneExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.datetime; 2 | 3 | import java.time.ZoneId; 4 | import java.time.ZonedDateTime; 5 | 6 | public class ZoneExample { 7 | public static void main(String[] args) { 8 | ZoneId.getAvailableZoneIds().stream() 9 | .forEach(System.out::println); 10 | 11 | System.out.println("Europe/London: " + ZonedDateTime.now(ZoneId.of("Europe/London"))); 12 | System.out.println("America/New_York: " + ZonedDateTime 13 | .now(ZoneId.of("America/New_York"))); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/Calculator.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 2 | 3 | public interface Calculator { 4 | //abstract sum method 5 | public int sum(int num1, int num2); 6 | 7 | //default method which is subtract 8 | default int subtract (int num1, int num2){ 9 | return num1 - num2; 10 | } 11 | 12 | static int multiply (int num1, int num2){ 13 | return num1 * num2; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/DefaultsStaticExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 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 DefaultsStaticExample { 9 | public static void main(String[] args) { 10 | List names = Arrays.asList("Mike", "Syed", "Jenny", "Gene", "Rajeev"); 11 | // Collections.sort(names); 12 | //System.out.println("names = " + names); 13 | 14 | names.sort(Comparator.naturalOrder()); 15 | System.out.println("names = " + names); 16 | 17 | 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/InterfaceA.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 2 | 3 | public interface InterfaceA { 4 | default void sumA(int num1, int num2){ 5 | System.out.println("InterfaceA.sumA " + (num1 + num2)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/InterfaceB.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 2 | 3 | public interface InterfaceB extends InterfaceA{ 4 | default void sumB(int num1, int num2){ 5 | System.out.println("InterfaceB.sumB " + (num1 + num2)); 6 | } 7 | 8 | default void sumA(int num1, int num2){ 9 | System.out.println("InterfaceB.sumA " + (num1 + num2)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/InterfaceC.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 2 | 3 | public interface InterfaceC { 4 | default void sumC(int num1, int num2){ 5 | System.out.println("InterfaceC.sumC " + (num1 + num2)); 6 | } 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/InterfaceD.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 2 | 3 | public interface InterfaceD { 4 | 5 | default void sumA(int num1, int num2){ 6 | System.out.println("InterfaceA.sumA " + (num1 + num2)); 7 | 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/MathOperationsExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 2 | 3 | public class MathOperationsExample implements Calculator { 4 | 5 | public static void main(String[] args) { 6 | MathOperationsExample mathOperationsExample = new MathOperationsExample(); 7 | System.out.println("Sum: " + mathOperationsExample.sum(2,4)); 8 | 9 | //our implementation using lambda expression for sum and divide 10 | Calculator calculator = (num1, num2) -> num1%num2; 11 | System.out.println("Calculator override using lambda " + calculator.sum(3,2)); 12 | 13 | System.out.println("Subtract: " + mathOperationsExample.subtract(4,2)); 14 | System.out.println("Multiply: " + Calculator.multiply(4,2)); 15 | 16 | } 17 | 18 | 19 | @Override 20 | public int sum(int num1, int num2) { 21 | return num1 + num2; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/MultipleIneritanceExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 2 | 3 | public class MultipleIneritanceExample implements InterfaceA, InterfaceB, InterfaceC { 4 | public static void main(String[] args) { 5 | MultipleIneritanceExample multipleIneritanceExample = new MultipleIneritanceExample(); 6 | multipleIneritanceExample.sumA(4,8); // resolve to child 7 | multipleIneritanceExample.sumB(2,4); 8 | multipleIneritanceExample.sumC(1,2); 9 | } 10 | 11 | // implemented class first 12 | // the sub interface that extends the interface 13 | 14 | public void sumA (int num1, int num2){ 15 | System.out.println("MultipleIneritanceExample.sumA" + (num1 + num2)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/com/modernjava/defaults/MultipleInheritanceDebuggingExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.defaults; 2 | 3 | public class MultipleInheritanceDebuggingExample implements InterfaceA, InterfaceD{ 4 | 5 | public void sumA (int num1, int num2){ 6 | System.out.println("MultipleInheritanceDebuggingExample.sumA" + (num1 + num2)) ; 7 | } 8 | 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/com/modernjava/factorymethods/FactoryMethodsExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.factorymethods; 2 | 3 | import java.util.*; 4 | 5 | public class FactoryMethodsExample { 6 | public static void main(String[] args) { 7 | //How we used to create unmodifiable list pre Java 9 8 | List names = new ArrayList(); 9 | names.add("Syed"); 10 | names.add("Mike"); 11 | names.add("Jenny"); 12 | names = Collections.unmodifiableList(names); 13 | System.out.println("names = " + names); 14 | 15 | //factory methods of Java 9 16 | List names2 = List.of("Syed", "Mike", "Jenny"); 17 | System.out.println("names2 = " + names2); 18 | Set set = Set.of("Syed", "Mike", "Jenny"); 19 | System.out.println("set = " + set); 20 | Map map = Map.of("Grade1", "Syed", "Grade2", "Mike"); 21 | System.out.println("map = " + map); 22 | //modify the list 23 | //names2.add("Gene"); 24 | // set= Set.of("Syed", "Syed", "Mike"); 25 | names.sort(Comparator.naturalOrder()); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/BiConsumerExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.BiConsumer; 4 | 5 | public class BiConsumerExample { 6 | public static void main(String[] args) { 7 | //printing two numbers 8 | BiConsumer biConsumer = (x,y) -> System.out.println("x: " + x + " y: " + y); 9 | biConsumer.accept(2,4); 10 | //calculating sum of two integers 11 | BiConsumer biConsumer1 = (x,y) -> System.out.println("x+y: " + (x+y)); 12 | biConsumer1.accept(2,4); 13 | 14 | //concatenate strings 15 | BiConsumer biConsumer2 = (x,y) -> System.out.println(x+y); 16 | biConsumer2.accept("Fell on", " deaf ears"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/BiConsumerExample2.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import org.w3c.dom.ls.LSOutput; 4 | 5 | import java.util.List; 6 | import java.util.function.BiConsumer; 7 | 8 | public class BiConsumerExample2 { 9 | public static void main(String[] args) { 10 | List instructors = Instructors.getAll(); 11 | //print out name and gender of instructors 12 | BiConsumer biConsumer = (name, gender) -> System.out.println("name is :" 13 | + name + " and gender is: " + gender); 14 | instructors.forEach(instructor -> 15 | biConsumer.accept(instructor.getName(), instructor.getGender())); 16 | 17 | //print out name and list of courses 18 | System.out.println("--------------------"); 19 | BiConsumer> biConsumer1 = (name, courses) -> System.out.println( 20 | "name is " + name + " courses: " + courses); 21 | instructors.forEach(instructor -> { 22 | biConsumer1.accept(instructor.getName(), instructor.getCourses()); 23 | }); 24 | 25 | //print out name and gender of all instructors who teaches online 26 | System.out.println("----------------------"); 27 | instructors.forEach(instructor -> { 28 | if (instructor.isOnlineCourses()) 29 | biConsumer.accept(instructor.getName(), instructor.getGender()); 30 | }); 31 | 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/BiFunctionExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.function.BiFunction; 7 | import java.util.function.Predicate; 8 | 9 | public class BiFunctionExample { 10 | public static void main(String[] args) { 11 | //Bifuction 2 inputs List and second is predicate which will filter if instructor has online 12 | //courses and return a map of string is name and Integer is the years of experience 13 | 14 | Predicate p1 = (i) -> i.isOnlineCourses()==true; 15 | BiFunction, Predicate, Map> mapBiFunction = 16 | ((instructors, instructorPredicate) -> { 17 | Map map = new HashMap<>(); 18 | instructors.forEach(instructor -> { 19 | if(instructorPredicate.test(instructor)){ 20 | map.put(instructor.getName(), instructor.getYearsOfExperience()); 21 | } 22 | }); 23 | return map; 24 | }); 25 | System.out.println(mapBiFunction.apply(Instructors.getAll(), p1)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/BiPredicateExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.List; 4 | import java.util.function.BiConsumer; 5 | import java.util.function.BiPredicate; 6 | import java.util.function.Predicate; 7 | 8 | public class BiPredicateExample { 9 | public static void main(String[] args) { 10 | List instructors = Instructors.getAll(); 11 | BiPredicate p3 = (online, experience) -> online==true && experience>10; 12 | 13 | //Biconsumer print name and courses 14 | BiConsumer> biConsumer = (name, courses) -> 15 | System.out.println("name is: " + name + " courses : " + courses); 16 | 17 | instructors.forEach(instructor -> { 18 | if(p3.test(instructor.isOnlineCourses(), instructor.getYearsOfExperience())) 19 | biConsumer.accept(instructor.getName(), instructor.getCourses()); 20 | }); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/BinaryOperatorExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.Comparator; 4 | import java.util.function.BinaryOperator; 5 | import java.util.function.DoubleBinaryOperator; 6 | import java.util.function.IntBinaryOperator; 7 | import java.util.function.LongBinaryOperator; 8 | 9 | public class BinaryOperatorExample { 10 | public static void main(String[] args) { 11 | BinaryOperator binaryOperator = (a,b) -> a + b; 12 | System.out.println(binaryOperator.apply(2,4)); 13 | 14 | Comparator comparator = (a,b) -> a.compareTo(b); 15 | BinaryOperator maxBi = BinaryOperator.maxBy(comparator); 16 | System.out.println(maxBi.apply(7,8)); 17 | 18 | BinaryOperator minBy = BinaryOperator.minBy(comparator); 19 | System.out.println(minBy.apply(7,8)); 20 | 21 | IntBinaryOperator intBi = (a,b) -> a*b; 22 | System.out.println(intBi.applyAsInt(2,4)); 23 | 24 | LongBinaryOperator longBi = (a,b) -> a*b; 25 | System.out.println(longBi.applyAsLong(20000000l, 22222222222222222l)); 26 | 27 | DoubleBinaryOperator doubleBi = (a,b) -> a*b; 28 | System.out.println(doubleBi.applyAsDouble(2222.22222, 22222222222222.22222)); 29 | 30 | 31 | 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/ConstructorReferenceExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ConstructorReferenceExample { 6 | public static void main(String[] args) { 7 | InstructorFactory instructorFactory = Instructor::new; 8 | Instructor instructor = instructorFactory.getInstructor("Mike", 10, "Software Developer" 9 | , "M", true, Arrays.asList("Java Programming", "C++ Programming", "Python Programming")); 10 | 11 | System.out.println(instructor); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/ConsumerExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.Consumer; 4 | 5 | public class ConsumerExample { 6 | public static void main(String[] args) { 7 | Consumer c = (x) -> System.out.println(x.length() + " the value of x: " + x); 8 | c.accept("Up in the air"); 9 | 10 | //Consumer with block statement 11 | Consumer d = (x) -> { 12 | System.out.println("x*x = " + x*x); 13 | System.out.println("x/x = " + x/x); 14 | }; 15 | d.accept(10); 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/ConsumerExample2.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.List; 4 | import java.util.function.Consumer; 5 | 6 | public class ConsumerExample2 { 7 | public static void main(String[] args) { 8 | List instructors = Instructors.getAll(); 9 | //looping through all the instructor and printing out the values of instructor 10 | Consumer c1 = (s1) -> System.out.println(s1); 11 | instructors.forEach(c1); 12 | 13 | //Loop through all the instructor and only print out their name 14 | System.out.println("---------------"); 15 | Consumer c2 = (s1) -> System.out.print(s1.getName()); 16 | instructors.forEach(c2); 17 | 18 | //Loop through all the instructors and print out their names and their courses 19 | System.out.println("----------------"); 20 | Consumer c3 = (s1) -> System.out.println(s1.getCourses()); 21 | instructors.forEach(c2.andThen(c3)); 22 | 23 | //Loop through all the instructors and print out their name if the years of experience is >10 24 | System.out.println("----------"); 25 | instructors.forEach(s1 -> { 26 | if(s1.yearsOfExperience>10){ 27 | c1.accept(s1); 28 | } 29 | }); 30 | 31 | //Loop through all the instructors and print out their name and years of experience if years 32 | //of experience is >5 and teaches course online 33 | System.out.println("--------------"); 34 | instructors.forEach(s1->{ 35 | if (s1.yearsOfExperience > 5 && !s1.isOnlineCourses()){ 36 | c1.andThen(c2).accept(s1); 37 | } 38 | }); 39 | 40 | 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/ConsumerExample3.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.DoubleConsumer; 4 | import java.util.function.IntConsumer; 5 | import java.util.function.LongConsumer; 6 | 7 | public class ConsumerExample3 { 8 | public static void main(String[] args) { 9 | IntConsumer intConsumer = (a) -> System.out.println(a*10); 10 | intConsumer.accept(10); 11 | 12 | LongConsumer longConsumer = (a) -> System.out.println(a * 10L); 13 | longConsumer.accept(10L); 14 | 15 | DoubleConsumer doubleConsumer = (a) -> System.out.println(a * 10); 16 | doubleConsumer.accept(10.50); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/ConvertToMethodReferenceExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.Predicate; 4 | 5 | public class ConvertToMethodReferenceExample { 6 | public static void main(String[] args) { 7 | Predicate p2 = ConvertToMethodReferenceExample::greaterThanTenYearsOfExperience; 8 | 9 | Instructors.getAll().forEach(instructor -> { 10 | if (p2.test(instructor)){ 11 | System.out.println(instructor); 12 | } 13 | }); 14 | } 15 | public static boolean greaterThanTenYearsOfExperience(Instructor instructor) { 16 | if (instructor.getYearsOfExperience()>10) 17 | return true; 18 | return false; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/FunctionExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.Function; 4 | 5 | public class FunctionExample { 6 | public static void main(String[] args) { 7 | Function sqrt = n -> Math.sqrt(n); 8 | System.out.println("Square root of 64: " + sqrt.apply(64)); 9 | System.out.println("Square root of 81: " + sqrt.apply(81)); 10 | 11 | Function lowercaseFunction = s1 -> s1.toLowerCase(); 12 | System.out.println(lowercaseFunction.apply("PROGRAMMING")); 13 | Function concatFunction = (s) -> s.concat(" In Java"); 14 | 15 | System.out.println(lowercaseFunction.andThen(concatFunction).apply("PROGRAMMING")); 16 | System.out.println(lowercaseFunction.compose(concatFunction).apply("PROGRAMMING")); 17 | 18 | 19 | 20 | 21 | 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/FunctionExample2.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.function.Function; 7 | import java.util.function.Predicate; 8 | 9 | public class FunctionExample2 { 10 | public static void main(String[] args) { 11 | //Map of instructors with name and years of experience 12 | //Function which will List and return a Map 13 | //Predicate will return true if instructor has online courses 14 | Predicate p1 = (i) -> i.isOnlineCourses()==true; 15 | Function, Map> mapFunction = (instructors -> { 16 | Map map = new HashMap<>(); 17 | instructors.forEach(instructor -> { 18 | if(p1.test(instructor)) { 19 | map.put(instructor.getName(), instructor.getYearsOfExperience()); 20 | } 21 | }); 22 | return map; 23 | }); 24 | 25 | System.out.println(mapFunction.apply(Instructors.getAll())); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/Instructor.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.List; 4 | 5 | public class Instructor { 6 | String name; 7 | int yearsOfExperience; 8 | String title; 9 | String gender; 10 | boolean onlineCourses; 11 | List courses; 12 | 13 | public Instructor(String name, int yearsOfExperience, String title, String gender, boolean onlineCourses, List courses) { 14 | this.name = name; 15 | this.yearsOfExperience = yearsOfExperience; 16 | this.title = title; 17 | this.gender = gender; 18 | this.onlineCourses = onlineCourses; 19 | this.courses = courses; 20 | } 21 | 22 | 23 | @Override 24 | public String toString() { 25 | return "Instructor{" + 26 | "name='" + name + '\'' + 27 | ", yearsOfExperience=" + yearsOfExperience + 28 | ", title='" + title + '\'' + 29 | ", gender='" + gender + '\'' + 30 | ", onlineCourses=" + onlineCourses + 31 | ", courses=" + courses + 32 | '}'; 33 | } 34 | 35 | public String getName() { 36 | return name; 37 | } 38 | 39 | public void setName(String name) { 40 | this.name = name; 41 | } 42 | 43 | public int getYearsOfExperience() { 44 | return yearsOfExperience; 45 | } 46 | 47 | public void setYearsOfExperience(int yearsOfExperience) { 48 | this.yearsOfExperience = yearsOfExperience; 49 | } 50 | 51 | public String getTitle() { 52 | return title; 53 | } 54 | 55 | public void setTitle(String title) { 56 | this.title = title; 57 | } 58 | 59 | public String getGender() { 60 | return gender; 61 | } 62 | 63 | public void setGender(String gender) { 64 | this.gender = gender; 65 | } 66 | 67 | public boolean isOnlineCourses() { 68 | return onlineCourses; 69 | } 70 | 71 | public void setOnlineCourses(boolean onlineCourses) { 72 | this.onlineCourses = onlineCourses; 73 | } 74 | 75 | public List getCourses() { 76 | return courses; 77 | } 78 | 79 | public void setCourses(List courses) { 80 | this.courses = courses; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/InstructorFactory.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.List; 4 | 5 | public interface InstructorFactory { 6 | Instructor getInstructor(String name, int yearsOfExperience, String title, 7 | String gender, boolean onlineCourse, List courses); 8 | } 9 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/Instructors.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class Instructors { 7 | 8 | public static List getAll(){ 9 | Instructor instructor1 = new Instructor("Mike", 10, "Software Developer" 10 | , "M", true, Arrays.asList("Java Programming", "C++ Programming", "Python Programming")); 11 | 12 | Instructor instructor2 = new Instructor("Jenny", 5, "Engineer" 13 | , "F", false, Arrays.asList("Multi-Threaded Programming", "CI/CD", "Unit Testing")); 14 | 15 | Instructor instructor3 = new Instructor("Gene", 6, "Manager" 16 | , "M", false, Arrays.asList("C++ Programming", "C Programming", "React Native")); 17 | 18 | Instructor instructor4 = new Instructor("Anthony", 15, "Senior Developer" 19 | , "M", true, Arrays.asList("Java Programming", "Angular Programming", "React Native")); 20 | 21 | Instructor instructor5 = new Instructor("Syed", 15, "Principal Engineer" 22 | , "M", true, Arrays.asList("Java Programming", "Java Multi-Threaded Programming", "React Native")); 23 | 24 | List list = Arrays.asList(instructor1,instructor2,instructor3,instructor4,instructor5); 25 | return list; 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/MethodReferenceExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.Function; 4 | import java.util.function.Predicate; 5 | 6 | public class MethodReferenceExample { 7 | public static void main(String[] args) { 8 | Predicate p1 = instructor -> instructor.isOnlineCourses(); 9 | Predicate p2 = Instructor::isOnlineCourses; 10 | 11 | Function sqrt= a -> Math.sqrt(a); 12 | Function sqrt1 = Math::sqrt; 13 | 14 | Function lowercaseFunction = s -> s.toLowerCase(); 15 | Function lowercaseFunction1 = String::toLowerCase; 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/PredicateAndBiConsumerExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.List; 4 | import java.util.function.BiConsumer; 5 | import java.util.function.Predicate; 6 | 7 | public class PredicateAndBiConsumerExample { 8 | public static void main(String[] args) { 9 | List instructors = Instructors.getAll(); 10 | //all instructor who teaches online 11 | Predicate p1 = (i) -> i.isOnlineCourses()==true; 12 | //instructor experience is >10 13 | Predicate p2 = (i) -> i.getYearsOfExperience()>10; 14 | 15 | //Biconsumer print name and courses 16 | BiConsumer> biConsumer = (name, courses) -> 17 | System.out.println("name is: " + name + " courses : " + courses); 18 | 19 | instructors.forEach(instructor -> { 20 | if(p1.and(p2).test(instructor)) 21 | biConsumer.accept(instructor.getName(), instructor.getCourses()); 22 | }); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/PredicateExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.Predicate; 4 | 5 | public class PredicateExample { 6 | public static void main(String[] args) { 7 | //if number is >10 return true other false 8 | Predicate p1 = (i) -> i>10; 9 | System.out.println(p1.test(100)); 10 | 11 | //i>10 && number is even number (i%2 ==0) 12 | Predicate p2 = (i) -> i%2==0; 13 | System.out.println(p1.and(p2).test(20)); 14 | 15 | //i>10 || number is even number (i%2==0) 16 | System.out.println(p1.or(p2).test(4)); 17 | 18 | //i>10 && i%2 !=0 19 | System.out.println(p1.and(p2.negate()).test(33)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/PredicateExample2.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.List; 4 | import java.util.function.Predicate; 5 | 6 | public class PredicateExample2 { 7 | public static void main(String[] args) { 8 | //all instructor who teaches online 9 | Predicate p1 = (i) -> i.isOnlineCourses()==true; 10 | //instructor experience is >10 years 11 | Predicate p2 = (i) -> i.getYearsOfExperience() >10; 12 | 13 | List instructors = Instructors.getAll(); 14 | instructors.forEach(instructor -> { 15 | if (p1.test(instructor)){ 16 | System.out.println(instructor); 17 | } 18 | }); 19 | 20 | // is instructor teaches online and exprience is > 10 years 21 | System.out.println("---------------------"); 22 | instructors.forEach(instructor -> { 23 | if(p1.and(p2).test(instructor)){ 24 | System.out.println(instructor); 25 | } 26 | }); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/PredicateExample3.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.DoublePredicate; 4 | import java.util.function.IntPredicate; 5 | import java.util.function.LongPredicate; 6 | 7 | public class PredicateExample3 { 8 | public static void main(String[] args) { 9 | IntPredicate p1 = (i) -> i>100; 10 | System.out.println(p1.test(100)); 11 | 12 | LongPredicate p2 = (i) -> i>100L; 13 | System.out.println(p2.test(1111111111111111111L)); 14 | 15 | DoublePredicate p3 = (i) -> i<100.25; 16 | DoublePredicate p4 = (i) -> i>100.10; 17 | System.out.println(p3.and(p4).test(100.15)); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/SupplierExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.Supplier; 4 | 5 | public class SupplierExample { 6 | public static void main(String[] args) { 7 | Supplier supplier = () -> (int) (Math.random() * 1000); 8 | System.out.println(supplier.get()); 9 | System.out.println(supplier.get()); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/Test.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | public class Test { 4 | public static void main (String args[]){ 5 | System.out.println("Hello World"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/UnaryOperatorExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.function.*; 4 | 5 | public class UnaryOperatorExample { 6 | 7 | public static void main(String[] args) { 8 | UnaryOperator unary = i -> i * 10; 9 | System.out.println(unary.apply(100)); 10 | 11 | Function function = i -> i*10; 12 | System.out.println(function.apply(100)); 13 | 14 | IntUnaryOperator intUnaryOperator = i -> i *10; 15 | System.out.println(intUnaryOperator.applyAsInt(100)); 16 | 17 | LongUnaryOperator longUnaryOperator = i -> i*10; 18 | System.out.println(longUnaryOperator.applyAsLong(10000000000000000l)); 19 | 20 | DoubleUnaryOperator doubleUnaryOperator = i -> i*10; 21 | System.out.println(doubleUnaryOperator.applyAsDouble(2000000.20000000)); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/VariableScope.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming; 2 | 3 | import java.util.List; 4 | import java.util.function.IntConsumer; 5 | 6 | public class VariableScope { 7 | static int k=0; 8 | public static void main(String[] args) { 9 | int b =10; //local variable 10 | IntConsumer intConsumer = (a) -> System.out.println(a*10); 11 | 12 | List instructors = Instructors.getAll(); 13 | instructors.forEach(instructor -> { 14 | System.out.println(instructor + " " + k); 15 | }); 16 | k++; 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/realexample/AccountFactory.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming.realexample; 2 | 3 | public interface AccountFactory { 4 | public abstract BankAccount getBankAccount(int id, double balance, String accountName); 5 | } 6 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/realexample/BankAccount.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming.realexample; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | import java.util.function.BiFunction; 6 | 7 | public class BankAccount { 8 | private int id; 9 | private double balance; 10 | private String accountName; 11 | final Lock lock = new ReentrantLock(); 12 | BiFunction subtractFunction = (a,b) -> a-b; 13 | BiFunction addFunction = (a,b) -> a + b; 14 | 15 | public BankAccount (int id, double balance, String accountName){ 16 | this.id = id; 17 | this.balance=balance; 18 | this.accountName = accountName; 19 | } 20 | 21 | public boolean withdraw (double amount) throws InterruptedException { 22 | if(this.lock.tryLock()){ 23 | Thread.sleep(100); 24 | balance = subtractFunction.apply(balance, amount); 25 | this.lock.unlock(); 26 | return true; 27 | } 28 | return false; 29 | } 30 | 31 | public boolean deposit (double amount) throws InterruptedException { 32 | if(this.lock.tryLock()){ 33 | Thread.sleep(100); 34 | balance= addFunction.apply(balance,amount); 35 | this.lock.unlock(); 36 | return true; 37 | } 38 | return false; 39 | } 40 | 41 | 42 | public boolean transfer (BankAccount to, double amount) throws InterruptedException { 43 | if(withdraw(amount)){ 44 | System.out.println("Withdrawing amount: " + amount + " from: " + getAccountName()); 45 | if(to.deposit(amount)){ 46 | System.out.println("Depositing amount:" + amount + " to: " + to.getAccountName()); 47 | return true; 48 | }else{ 49 | System.out.println("Failed to acquire both locks: refunding " + amount + " to: " + accountName); 50 | while (!deposit(amount)) 51 | continue; 52 | } 53 | } 54 | return false; 55 | } 56 | 57 | 58 | @Override 59 | public String toString() { 60 | return "BankAccount{" + 61 | "id=" + id + 62 | ", balance=" + balance + 63 | ", accountName='" + accountName + '\'' + 64 | '}'; 65 | } 66 | 67 | public int getId() { 68 | return id; 69 | } 70 | 71 | public void setId(int id) { 72 | this.id = id; 73 | } 74 | 75 | public double getBalance() { 76 | return balance; 77 | } 78 | 79 | public void setBalance(double balance) { 80 | this.balance = balance; 81 | } 82 | 83 | public String getAccountName() { 84 | return accountName; 85 | } 86 | 87 | public void setAccountName(String accountName) { 88 | this.accountName = accountName; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/com/modernjava/funcprogramming/realexample/BankTransfer.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.funcprogramming.realexample; 2 | 3 | import java.util.concurrent.Executor; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.TimeUnit; 7 | import java.util.function.BiConsumer; 8 | import java.util.function.BiPredicate; 9 | 10 | public class BankTransfer { 11 | public static void main(String[] args) { 12 | AccountFactory accountFactory = BankAccount::new; 13 | BankAccount studentBankAccount = accountFactory.getBankAccount(1, 50000, "StudentA"); 14 | BankAccount universityBankAccount = accountFactory.getBankAccount(2, 100000, "University"); 15 | 16 | BiPredicate p1 = (balance, amount) -> balance > amount; 17 | BiConsumer printer = (x, y) -> System.out.println(x + y); 18 | BiConsumer printer2 = (student, university) -> 19 | System.out.println("Ending balance of student account: " + studentBankAccount.getBalance() + 20 | " University account: " + universityBankAccount.getBalance()); 21 | 22 | ExecutorService service = Executors.newFixedThreadPool(10); 23 | 24 | Thread t1 = new Thread(() -> { 25 | System.out.println(Thread.currentThread().getName() + " says :: Executing Transfer"); 26 | try { 27 | double amount = 1000; 28 | if (!p1.test(studentBankAccount.getBalance(), amount)) { 29 | printer.accept(Thread.currentThread().getName() + "says :: balance insufficient, ", amount); 30 | return; 31 | } 32 | while (!studentBankAccount.transfer(universityBankAccount, amount)) { 33 | TimeUnit.MILLISECONDS.sleep(100); 34 | continue; 35 | } 36 | } catch (InterruptedException ie) { 37 | ie.printStackTrace(); 38 | } 39 | printer.accept(Thread.currentThread().getName() + " says transfer is successful: Balance in account ", 40 | universityBankAccount.getBalance()); 41 | }); 42 | 43 | for (int i = 0; i < 20; i++) { 44 | service.submit(t1); 45 | } 46 | service.shutdown(); 47 | 48 | try { 49 | while (!service.awaitTermination(24L, TimeUnit.HOURS)) { 50 | System.out.println("Not Yet. Still waiting for termination"); 51 | } 52 | } catch (InterruptedException iee) { 53 | iee.printStackTrace(); 54 | } 55 | printer2.accept(studentBankAccount, universityBankAccount); 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /src/com/modernjava/java9improvements/MultiLineTextBlockExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.java9improvements; 2 | 3 | public class MultiLineTextBlockExample { 4 | public static void main(String[] args) { 5 | String st1 = """ 6 | Hello World 7 | Using 8 | text blocks !"""; 9 | 10 | System.out.println("st1 = " + st1); 11 | 12 | String phrase = """ 13 | { 14 | employee : "Mike", 15 | employeeId: 10001; 16 | employeeType: FT 17 | } 18 | """; 19 | System.out.println("phrase = " + phrase); 20 | 21 | String html = """ 22 | 23 | 24 |

"Java, Programming"

25 | 26 | 27 | """; 28 | 29 | System.out.println("html = " + html); 30 | 31 | String st2 = st1.concat("This is my first text block"); 32 | System.out.println("st2 = " + st2); 33 | 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/modernjava/java9improvements/SafeArgsExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.java9improvements; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class SafeArgsExample { 8 | 9 | private void print(List... names) { 10 | for (List name : names) { 11 | System.out.println(name); 12 | } 13 | } 14 | public static void main(String[] args) { 15 | SafeArgsExample safeArgsExample = new SafeArgsExample(); 16 | List list = new ArrayList(); 17 | list.add("Syed"); 18 | list.add("Mike"); 19 | list.add("Jenny"); 20 | safeArgsExample.print(list); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/com/modernjava/java9improvements/SwitchExpressionEnhancementExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.java9improvements; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class SwitchExpressionEnhancementExample { 6 | public static void main(String[] args) { 7 | String month="JANUARY"; 8 | String quarter = switch(month){ 9 | case "JANUARY", "FEBURARY", "MARCH" ->{ 10 | var isLeapYear = LocalDate.now().isLeapYear(); 11 | yield (isLeapYear ? "FIRST QUARTER - LEAP YEAR": "FIRST QUARTER"); 12 | } 13 | case "APRIL", "MAY", "JUNE" -> "SECOND QUARTER"; 14 | case "JULY", "AUGUST", "SEPTEMBER" -> "THIRD QUARTER"; 15 | case "OCTOBER", "NOVEMBER", "DECEMBER" -> "FOURTH QUARTER"; 16 | default -> "UNKNOWN QUARTER"; 17 | }; 18 | System.out.println("quarter = " + quarter); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/com/modernjava/java9improvements/SwitchExpressionExample2.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.java9improvements; 2 | 3 | public class SwitchExpressionExample2 { 4 | public static void main(String[] args) { 5 | String month="JANUARY"; 6 | switch (month){ 7 | case "JANUARY", "FEBURARY", "MARCH" -> System.out.println("FIRST QUARTER"); 8 | case "APRIL", "MAY", "JUNE" -> System.out.println("SECOND QUARTER"); 9 | case "JULY", "AUGUST", "SEPTEMBER"-> System.out.println("THIRD QUARTER"); 10 | case "OCTOBER", "NOVEMBER", "DECEMBER" -> System.out.println("FOURTH QUARTER"); 11 | default -> System.out.println("UNKNOWN QUARTER"); 12 | } 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/com/modernjava/java9improvements/SwitchExpressionsExample1.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.java9improvements; 2 | 3 | import java.time.LocalDate; 4 | 5 | public class SwitchExpressionsExample1 { 6 | public static void main(String[] args) { 7 | String month="JANUARY"; 8 | String quarter = switch(month){ 9 | case "JANUARY", "FEBURARY", "MARCH" -> { 10 | var isLeapYear = LocalDate.now().isLeapYear(); 11 | yield (isLeapYear ? "FIRST QUARTER - LEAP YEAR": "FIRST QUARTER"); 12 | } 13 | case "APRIL", "MAY", "JUNE" -> "SECOND QUARTER"; 14 | case "JULY", "AUGUST", "SEPTEMBER" -> "THIRD QUARTER"; 15 | case "OCTOBER", "NOVEMBER", "DECEMBER" -> "FOURTH QUARTER"; 16 | default -> "UNKNOWN QUARTER"; 17 | }; 18 | System.out.println("quarter = " + quarter); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/com/modernjava/java9improvements/SwitchStatementExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.java9improvements; 2 | 3 | public class SwitchStatementExample { 4 | public static void main(String[] args) { 5 | String month="JANUARY"; 6 | String quarter; 7 | switch (month){ 8 | case "JANUARY": 9 | quarter = "FIRST QUARTER"; 10 | break; 11 | case "FEBURARY": 12 | quarter = "FIRST QUARTER"; 13 | break; 14 | case "MARCH": 15 | quarter = "FIRST QUARTER"; 16 | break; 17 | case "APRIL": 18 | quarter = "SECOND QUARTER"; 19 | break; 20 | case "MAY": 21 | quarter = "SECOND QUARTER"; 22 | break; 23 | case "JUNE": 24 | quarter = "SECOND QUARTER"; 25 | case "JULY": 26 | quarter = "THIRD QUARTER"; 27 | break; 28 | case "AUGUST": 29 | quarter = "THIRD QUARTER"; 30 | break; 31 | case "SEPTEMBER": 32 | quarter = "THIRD QUARTER"; 33 | break; 34 | case "OCTOBER": 35 | quarter = "FORTH QUARTER"; 36 | break; 37 | case "NOVEMBER": 38 | quarter = "FOURTH QUARTER"; 39 | break; 40 | case "DECEMBER": 41 | quarter = "FOURTH QUARTER"; 42 | break; 43 | default: 44 | quarter= "UNKNOWN QUARTER"; 45 | break; 46 | } 47 | System.out.println("quarter = " + quarter); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/com/modernjava/java9improvements/TryWithResourcesExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.java9improvements; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.Reader; 6 | import java.io.StringReader; 7 | import java.nio.Buffer; 8 | 9 | public class TryWithResourcesExample { 10 | public static void main(String[] args) throws IOException { 11 | //java 8 12 | Reader inputString = new StringReader("Don't cut any corners"); 13 | BufferedReader bufferedReader = new BufferedReader(inputString); 14 | try(BufferedReader bufferedReader1=bufferedReader){ 15 | System.out.println("bufferedReader1.readLine() = " 16 | + bufferedReader1.readLine()); 17 | } 18 | 19 | //java 9 20 | Reader inputString2 = new StringReader("Hang in there"); 21 | BufferedReader bufferedReader2 = new BufferedReader(inputString2); 22 | try(bufferedReader2){ 23 | System.out.println("bufferedReader2.readLine() = " 24 | + bufferedReader2.readLine()); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/modernjava/javaimprovements/AsyncHttpClient.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.javaimprovements; 2 | 3 | import java.net.URI; 4 | import java.net.http.HttpClient; 5 | import java.net.http.HttpRequest; 6 | import java.net.http.HttpResponse; 7 | import java.util.concurrent.CompletableFuture; 8 | import java.util.concurrent.ExecutionException; 9 | 10 | public class AsyncHttpClient { 11 | public static void main(String[] args) throws ExecutionException, InterruptedException { 12 | HttpClient client = HttpClient.newHttpClient(); 13 | HttpRequest request = HttpRequest.newBuilder() 14 | .uri(URI.create("https://www.ldapsoft.com")) 15 | .build(); 16 | 17 | CompletableFuture response = 18 | client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) 19 | .thenApply(HttpResponse::body) 20 | .thenAccept(System.out::println); 21 | response.get(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/com/modernjava/javaimprovements/HttpClientExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.javaimprovements; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.net.http.HttpClient; 6 | import java.net.http.HttpRequest; 7 | import java.net.http.HttpResponse; 8 | 9 | public class HttpClientExample { 10 | public static void main(String[] args) throws IOException, InterruptedException { 11 | HttpClient client = HttpClient.newHttpClient(); 12 | HttpRequest request = HttpRequest.newBuilder() 13 | .uri(URI.create("https://www.ldapsoft.com")) 14 | .build(); 15 | 16 | HttpResponse response = client.send( 17 | request,HttpResponse.BodyHandlers.ofString()); 18 | 19 | System.out.println("response.body() = " + response.body()); 20 | 21 | } 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/com/modernjava/javaimprovements/TypeInterferenceExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.javaimprovements; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | 8 | public class TypeInterferenceExample { 9 | 10 | public static void main(String[] args) { 11 | //String 12 | //String name = "Mike"; 13 | var name = "Mike"; 14 | System.out.println("name = " + name); 15 | 16 | var dateTime = LocalDateTime.now(); // LocalDateTime dateTime = LocalDateTime.now(); 17 | System.out.println("dateTime = " + dateTime); 18 | 19 | HashMap map = new HashMap<>(); 20 | var map1 = new HashMap(); 21 | 22 | //integer array 23 | int[] numbers = {1,2,3,4,5}; 24 | var numbers1 = new int[] {1,2,3,4,5}; 25 | 26 | //list 27 | List names = new ArrayList<>(); 28 | names.add("Syed"); 29 | names.add("Mike"); 30 | System.out.println("names = " + names); 31 | 32 | var names1 = new ArrayList<>(); 33 | names1.add("Gene"); 34 | names1.add(1.0001); 35 | names1.add(1); 36 | System.out.println("names1 = " + names1); 37 | 38 | // 39 | var integers = List.of(1,2,3,4,5); 40 | integers.forEach(System.out::println); 41 | 42 | //int num = 999999999999999L; 43 | var num = 99999999999999999.99999; 44 | 45 | var result = 9/2; //4 46 | System.out.println("result = " + result); 47 | 48 | var result1 = 9.0/2; 49 | System.out.println("result1 = " + result1); 50 | 51 | result1 = 11d/2d; 52 | System.out.println("result1 = " + result1); 53 | 54 | var idiomOfTheDay = "A blessing in disguise"; 55 | printString(idiomOfTheDay); 56 | 57 | 58 | } 59 | 60 | public static void printString (String toPrint){ 61 | System.out.println("toPrint = " + toPrint); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/com/modernjava/javaimprovements/VarWithLambdaExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.javaimprovements; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.List; 7 | import java.util.function.BiFunction; 8 | import java.util.function.Predicate; 9 | 10 | public class VarWithLambdaExample { 11 | public static void main(String[] args) { 12 | var instructors = Instructors.getAll(); 13 | Predicate experiencePredicate = (var s) -> 14 | s.getYearsOfExperience()>10; 15 | instructors.forEach(instructor -> { 16 | if(experiencePredicate.test(instructor)){ 17 | var result = instructor.getName(); 18 | System.out.println("result = " + result); 19 | } 20 | }); 21 | 22 | BiFunction sum = (var x, var y) -> x + y; 23 | System.out.println("sum.apply(2,4) = " + sum.apply(2,4)); 24 | 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/ComparatorExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 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 ComparatorExample { 9 | public static void main(String[] args) { 10 | Book book1 = new Book ("Java Programming", 32.50f); 11 | Book book2 = new Book ("Java Multithreading" , 42.75f); 12 | Book book3 = new Book ("Python Programming" , 50.75f); 13 | Book book4 = new Book ("C++ Programming", 25.25f); 14 | 15 | List listBooks = Arrays.asList(book1, book2,book3,book4); 16 | 17 | //Comparator using traditional way 18 | Comparator priceComparator = new Comparator() { 19 | @Override 20 | public int compare(Book book1, Book book2) { 21 | return (int) (book2.getPrice() - book1.getPrice()); 22 | } 23 | }; 24 | 25 | 26 | System.out.println(listBooks); 27 | //Collections.sort(listBooks, priceComparator); 28 | Collections.sort(listBooks, (Book b1, Book b2) -> (int) (b2.getPrice() - b1.getPrice())); 29 | System.out.println("After sorting the books"); 30 | System.out.println(listBooks); 31 | } 32 | } 33 | 34 | class Book { 35 | private String title; 36 | private float price; 37 | 38 | public Book (String title, float price){ 39 | this.title=title; 40 | this.price=price; 41 | } 42 | 43 | public String getTitle() { 44 | return title; 45 | } 46 | 47 | public void setTitle(String title) { 48 | this.title = title; 49 | } 50 | 51 | public float getPrice() { 52 | return price; 53 | } 54 | 55 | public void setPrice(float price) { 56 | this.price = price; 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return "Book{" + 62 | "title='" + title + '\'' + 63 | ", price=" + price + 64 | '}'; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/ConcatenateInterface.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | @FunctionalInterface 4 | public interface ConcatenateInterface { 5 | //abstract method 6 | public String sconcat (String a, String b); 7 | } 8 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/ConcetanateTraditional.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | public class ConcetanateTraditional implements ConcatenateInterface{ 4 | @Override 5 | public String sconcat(String a, String b) { 6 | return a + " " + b; 7 | } 8 | 9 | public static void main(String[] args) { 10 | ConcetanateTraditional concetanateTraditional = new ConcetanateTraditional(); 11 | System.out.println(concetanateTraditional.sconcat("Hello", "World")); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/ConcetenateLambda.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | public class ConcetenateLambda { 4 | 5 | public static void main(String[] args) { 6 | ConcatenateInterface concatenateInterface = (a,b) -> a + " " + b; 7 | System.out.println(concatenateInterface.sconcat("Hello", "World")); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/HelloWorldInterface.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | public interface HelloWorldInterface { 4 | //abstract method as it does not provide implementation 5 | public String sayHelloWorld(); 6 | 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/HelloWorldLambda.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | public class HelloWorldLambda { 4 | public static void main(String[] args) { 5 | //implementing sayHelloWorld Using Lambda 6 | HelloWorldInterface helloWorldInterface = () -> "Hello World"; 7 | 8 | 9 | System.out.println(helloWorldInterface.sayHelloWorld()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/HelloWorldTraditional.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | public class HelloWorldTraditional implements HelloWorldInterface { 4 | @Override 5 | public String sayHelloWorld() { 6 | return "Hello World"; 7 | } 8 | 9 | public static void main(String[] args) { 10 | HelloWorldTraditional helloWorldTraditional = new HelloWorldTraditional(); 11 | System.out.println(helloWorldTraditional.sayHelloWorld()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/IncrementByFiveInterface.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | @FunctionalInterface 4 | public interface IncrementByFiveInterface { 5 | //abstract method 6 | public int incrementByFive(int a); 7 | } 8 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/IncrementByFiveLambda.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | public class IncrementByFiveLambda { 4 | public static void main(String[] args) { 5 | IncrementByFiveInterface incrementByFiveInterface = (x) -> x + 5; 6 | System.out.println(incrementByFiveInterface.incrementByFive(2)); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/IncrementByFiveTraditional.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | public class IncrementByFiveTraditional implements IncrementByFiveInterface{ 4 | @Override 5 | public int incrementByFive(int a) { 6 | return a + 5; 7 | } 8 | 9 | public static void main(String[] args) { 10 | IncrementByFiveTraditional incrementByFiveTraditional = new IncrementByFiveTraditional(); 11 | System.out.println(incrementByFiveTraditional.incrementByFive(2)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/RunnableExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | public class RunnableExample { 4 | public static void main(String[] args) { 5 | //Runnable Traditional example 6 | Runnable runnable = new Runnable() { 7 | @Override 8 | public void run() { 9 | int sum = 0; 10 | for (int i = 0; i < 10; i++) 11 | sum += i; 12 | System.out.println("Traditional: " + sum); 13 | } 14 | }; 15 | new Thread(runnable).start(); 16 | 17 | //Implement using Lambda 18 | Runnable runnable1 = () -> { 19 | int sum = 0; 20 | for (int i = 0; i < 10; i++) 21 | sum += i; 22 | System.out.println("Runnable Lambda: " + sum); 23 | }; 24 | 25 | new Thread(runnable1).start(); 26 | 27 | //Implement using Thread with lambda 28 | new Thread(() -> { 29 | int sum = 0; 30 | for (int i = 0; i < 10; i++) 31 | sum = sum + i; 32 | System.out.println("Thread Lambda: " + sum); 33 | 34 | }).start(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/modernjava/lambda/SumOfNumbersUsingCallable.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.lambda; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.concurrent.*; 6 | import java.util.stream.IntStream; 7 | 8 | public class SumOfNumbersUsingCallable { 9 | public static int[] array = IntStream.rangeClosed(0,5000).toArray(); 10 | public static int total = IntStream.rangeClosed(0,5000).sum(); 11 | 12 | public static void main(String[] args) throws InterruptedException, ExecutionException { 13 | Callable callable1 = () -> { 14 | int sum=0; 15 | for (int i=0;i< array.length/2;i++){ 16 | sum = sum + array[i]; 17 | } 18 | return sum; 19 | }; 20 | 21 | Callable callable2 = () -> { 22 | int sum = 0; 23 | for (int i=array.length/2; i> taskList = Arrays.asList(callable1, callable2); 31 | List> results = executorService.invokeAll(taskList); 32 | 33 | int k=0; 34 | int sum=0; 35 | for (Future result: results){ 36 | sum = sum + result.get(); 37 | System.out.println("Sum of " + ++k + " is: " + result.get()); 38 | } 39 | System.out.println("Sum from the Callable is: " + sum); 40 | System.out.println("Correct sum from InStream is: " + total); 41 | executorService.shutdown(); 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/com/modernjava/optional/OptionalExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.optional; 2 | 3 | import java.util.Arrays; 4 | import java.util.Optional; 5 | 6 | public class OptionalExample { 7 | public static void main(String[] args) { 8 | // Integer[] numbers = new Integer[10]; 9 | // int number = numbers[1].intValue(); 10 | // System.out.println("number = " + number); 11 | 12 | Optional optionalString = Optional.of("Hello World"); 13 | System.out.println("optionalString = " + optionalString); 14 | 15 | System.out.println("getWords:" + getWords()); 16 | 17 | } 18 | 19 | public static Optional getWords() { 20 | String[] words = new String[10]; 21 | Optional optionalS = Optional.ofNullable(words[1]); 22 | if (optionalS.isPresent()) 23 | return optionalS; 24 | else 25 | return Optional.empty(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/modernjava/optional/OptionalIfIsExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.optional; 2 | 3 | import java.util.Optional; 4 | 5 | public class OptionalIfIsExample { 6 | public static void main(String[] args) { 7 | //isPresent 8 | Optional stringOptional = Optional.ofNullable("Hello World"); 9 | if(stringOptional.isPresent()) 10 | System.out.println("stringOptional = " + stringOptional); 11 | 12 | stringOptional.ifPresent(s -> System.out.println("s = " + s)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/com/modernjava/optional/OptionalOfEmptyExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.optional; 2 | 3 | import javax.swing.text.html.Option; 4 | import java.util.Optional; 5 | 6 | public class OptionalOfEmptyExample { 7 | public static void main(String[] args) { 8 | Optional optionalString = Optional.of("Hello World"); 9 | System.out.println("optionalString = " + optionalString); 10 | 11 | System.out.println("getWords: " + getWords()); 12 | } 13 | 14 | public static Optional getWords(){ 15 | String[] words = new String[10]; 16 | words[1]= "test"; 17 | Optional optionalS = Optional.ofNullable(words[1]); 18 | if(optionalS.isPresent()) 19 | return optionalS; 20 | else 21 | return Optional.empty(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/com/modernjava/optional/OptionalOrElseThrowExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.optional; 2 | 3 | import java.util.Optional; 4 | 5 | public class OptionalOrElseThrowExample { 6 | public static void main(String[] args) { 7 | //orElse 8 | Integer[] numbers = new Integer[10]; 9 | numbers[0] = 1; 10 | Optional number = Optional.ofNullable(numbers[0]); 11 | int result = number.orElse(-1); 12 | System.out.println("result = " + result); 13 | 14 | //orElseGet 15 | result = number.orElseGet(() -> -1); 16 | System.out.println("result - orElseGet = " + result); 17 | 18 | //orElseThrow 19 | try { 20 | result = number.orElseThrow(Exception::new); 21 | System.out.println("result orElseThrow = " + result); 22 | } catch (Exception e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/com/modernjava/parallelstream/ParallelStreamExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.parallelstream; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | public class ParallelStreamExample { 6 | public static void main(String[] args) { 7 | System.out.println("Sum Sequential: " + sumSequentialStream()); 8 | System.out.println("Sum Parallel: " + sumParallelStream()); 9 | 10 | } 11 | 12 | public static int sumSequentialStream(){ 13 | return IntStream.rangeClosed(0,50000).sum(); 14 | } 15 | 16 | public static int sumParallelStream(){ 17 | return IntStream.rangeClosed(0,50000).parallel().sum(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/modernjava/parallelstream/StreamPerformanceExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.parallelstream; 2 | 3 | import java.util.function.Supplier; 4 | import java.util.stream.IntStream; 5 | 6 | public class StreamPerformanceExample { 7 | public static void main(String[] args) { 8 | int loop = 20; 9 | long result = measurePerformance(StreamPerformanceExample::sumSequentialStream,loop); 10 | System.out.println("Time Taken to process sum in sequential: " 11 | + result + "in msecs"); 12 | result = measurePerformance(StreamPerformanceExample::sumParallelStream,loop); 13 | System.out.println("Time Takes to process sum in Parallel: " + result + " in msecs"); 14 | 15 | } 16 | 17 | public static long measurePerformance (Supplier supplier, int numberOfTimes){ 18 | long startTime= System.currentTimeMillis(); 19 | for (int i=0;i supplier, int numberofTimes){ 23 | long startTime = System.currentTimeMillis(); 24 | for (int i=0;i randomTokens = LongStream.rangeClosed(0,tokenCount) 31 | .mapToObj((i) ->{ 32 | return new RandomTokens(i, ThreadLocalRandom.current() 33 | .nextLong(tokenCount)); 34 | }).collect(Collectors.toList()); 35 | randomTokens.stream().sorted(Comparator.comparing(RandomTokens::getTokens)); 36 | return -1; 37 | 38 | } 39 | 40 | public static long sortParallelStream(){ 41 | List randomTokens = LongStream.rangeClosed(0,tokenCount) 42 | .parallel().mapToObj((i) ->{ 43 | return new RandomTokens(i, ThreadLocalRandom.current() 44 | .nextLong(tokenCount)); 45 | }).collect(Collectors.toList()); 46 | randomTokens.stream().parallel().sorted(Comparator.comparing(RandomTokens::getTokens)); 47 | return -1; 48 | } 49 | } 50 | 51 | class RandomTokens{ 52 | long id; 53 | long tokens; 54 | 55 | public RandomTokens(long id, long tokens) { 56 | this.id = id; 57 | this.tokens = tokens; 58 | } 59 | 60 | public long getId() { 61 | return id; 62 | } 63 | 64 | public void setId(long id) { 65 | this.id = id; 66 | } 67 | 68 | public long getTokens() { 69 | return tokens; 70 | } 71 | 72 | public void setTokens(long tokens) { 73 | this.tokens = tokens; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/BoxingUnBoxingExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.IntStream; 7 | 8 | public class BoxingUnBoxingExample { 9 | public static void main(String[] args) { 10 | List numbers; 11 | 12 | IntStream numStream = IntStream.rangeClosed(0,5000); //primitive int stream 13 | numbers = numStream.boxed().collect(Collectors.toList()); 14 | numbers.forEach(System.out::println); 15 | 16 | Optional sum = numbers.stream().reduce((a,b)-> a + b); 17 | if (sum.isPresent()) 18 | System.out.println (sum.get()); 19 | 20 | int sum1 = numbers.stream().mapToInt(Integer::intValue).sum(); 21 | System.out.println(sum1); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/CollectorMappingExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.stream.Collectors; 9 | 10 | public class CollectorMappingExample { 11 | public static void main(String[] args) { 12 | //map 13 | List namesList = Instructors.getAll().stream() 14 | .map(Instructor::getName) 15 | .collect(Collectors.toList()); 16 | namesList.forEach(System.out::println); 17 | 18 | //mapping 19 | namesList= Instructors.getAll().stream() 20 | .collect(Collectors.mapping(Instructor::getName, Collectors.toList())); 21 | 22 | namesList.forEach(System.out::println); 23 | 24 | //Instructors by their years of experience 25 | Map> mapYearsOfExperienceAndNames = Instructors.getAll().stream() 26 | .collect(Collectors.groupingBy(Instructor::getYearsOfExperience, 27 | Collectors.mapping(Instructor::getName, Collectors.toList()))); 28 | 29 | mapYearsOfExperienceAndNames.forEach((key,value) ->{ 30 | System.out.println("key = " + key + " value = " + value); 31 | }); 32 | 33 | 34 | 35 | 36 | 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/CollectorSummingAveragingExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.stream.Collectors; 7 | 8 | public class CollectorSummingAveragingExample { 9 | public static void main(String[] args) { 10 | //sum of years of experience of all instructor 11 | int sum = Instructors.getAll().stream() 12 | .collect(Collectors.summingInt(Instructor::getYearsOfExperience)); 13 | 14 | System.out.println("sum = " + sum); 15 | 16 | //calculate average of years of experience of all instructors 17 | double average = Instructors.getAll().stream() 18 | .collect(Collectors.averagingInt(Instructor::getYearsOfExperience)); 19 | 20 | System.out.println("average = " + average); 21 | 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/CollectorsMinMaxExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.Comparator; 7 | import java.util.Optional; 8 | import java.util.stream.Collectors; 9 | 10 | public class CollectorsMinMaxExample { 11 | public static void main(String[] args) { 12 | //instructor with minimum years of experience 13 | Optional instructor = Instructors.getAll().stream() 14 | .collect(Collectors.minBy(Comparator.comparing( 15 | Instructor::getYearsOfExperience))); 16 | System.out.println("instructor = " + instructor); 17 | System.out.println("---------------"); 18 | 19 | instructor = Instructors.getAll().stream() 20 | .min(Comparator.comparing(Instructor::getYearsOfExperience)); 21 | System.out.println("instructor = " + instructor); 22 | 23 | instructor = Instructors.getAll().stream() 24 | .collect(Collectors.maxBy(Comparator.comparing( 25 | Instructor::getYearsOfExperience))); 26 | System.out.println("instructor = " + instructor); 27 | System.out.println("---------------"); 28 | 29 | instructor = Instructors.getAll().stream() 30 | .max(Comparator.comparing(Instructor::getYearsOfExperience)); 31 | System.out.println("instructor = " + instructor); 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/CountingExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.stream.Collectors; 7 | 8 | public class CountingExample { 9 | public static void main(String[] args) { 10 | //count the numbers of instructors who teaches online courses 11 | //stream.count 12 | long count = Instructors.getAll().stream() 13 | .filter(Instructor::isOnlineCourses) 14 | .count(); 15 | System.out.println(count); 16 | 17 | 18 | //collectors.counting 19 | count = Instructors.getAll().stream() 20 | .filter(Instructor::isOnlineCourses) 21 | .collect(Collectors.counting()); 22 | System.out.println("count = " + count); 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/DoubleStreamExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.Random; 4 | import java.util.stream.DoubleStream; 5 | import java.util.stream.LongStream; 6 | 7 | public class DoubleStreamExample { 8 | public static void main(String[] args) { 9 | //of 10 | DoubleStream numbers = DoubleStream.of(1.2,2.2,3.3,4.4,5.5); 11 | numbers.forEach(System.out::println); 12 | System.out.println("--------------"); 13 | 14 | //iterate 15 | numbers = DoubleStream.iterate(0,i->i+2.0).limit(5); 16 | numbers.forEach(System.out::println); 17 | System.out.println("--------------"); 18 | 19 | //generate 20 | numbers = DoubleStream.generate(new Random()::nextDouble).limit(5); 21 | numbers.forEach(System.out::println); 22 | System.out.println("--------------"); 23 | 24 | //range 25 | numbers = LongStream.range(1,5).asDoubleStream(); 26 | numbers.forEach(System.out::println); 27 | System.out.println("--------------"); 28 | 29 | //rangeClosed 30 | numbers = LongStream.rangeClosed(1,5).asDoubleStream(); 31 | numbers.forEach(System.out::println); 32 | System.out.println("--------------"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/FilterExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.Comparator; 7 | import java.util.List; 8 | import java.util.stream.Collectors; 9 | 10 | public class FilterExample { 11 | public static void main(String[] args) { 12 | //returning instructors sorted by their name and have more that 10 years of experience 13 | 14 | List list = Instructors.getAll().stream() 15 | .filter(instructor -> instructor.getYearsOfExperience()>10) 16 | .sorted(Comparator.comparing(Instructor::getName)) 17 | .collect(Collectors.toList()); 18 | 19 | list.forEach(System.out::println); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/FlatMapExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.List; 7 | import java.util.Set; 8 | import java.util.stream.Collectors; 9 | 10 | public class FlatMapExample { 11 | public static void main(String[] args) { 12 | //Get a list of all the courses which instructors offers 13 | Set instructorsCourses = Instructors.getAll().stream() 14 | .map(Instructor::getCourses) 15 | .flatMap(List::stream) 16 | .collect(Collectors.toSet()); 17 | System.out.println(instructorsCourses); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/GroupingByExample1.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.sql.SQLOutput; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.stream.Collectors; 10 | 11 | public class GroupingByExample1 { 12 | public static void main(String[] args) { 13 | //group list of name by their length 14 | List names = List.of("Syed", "Mike", "Jenny", "Gene", "Rajeev"); 15 | Map> result = names.stream() 16 | .collect(Collectors.groupingBy(String::length)); 17 | System.out.println("result = " + result); 18 | 19 | System.out.println("-----------------"); 20 | //grouping by instructors by their gender 21 | Map> instructorByGender = Instructors.getAll() 22 | .stream().collect(Collectors.groupingBy(Instructor::getGender)); 23 | 24 | instructorByGender.forEach((key,value) -> { 25 | System.out.println("key = " + key + " value = " + value); 26 | }); 27 | System.out.println("-----------------"); 28 | //grouping by experience where >10 years of experience is classified 29 | //as Senior and others are junior 30 | Map> instructorsByExperience = Instructors.getAll() 31 | .stream().collect(Collectors.groupingBy(instructor -> instructor 32 | .getYearsOfExperience()>10 ? "SENIOR": "JUNIOR")); 33 | 34 | instructorsByExperience.forEach((key,value) -> { 35 | System.out.println("key = " + key + " value = " + value); 36 | }); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/GroupingExample2.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.stream.Collectors; 9 | 10 | public class GroupingExample2 { 11 | public static void main(String[] args) { 12 | //grouping by length of string and also checking that the names contains e 13 | //and only return those name which has e in it 14 | List name = List.of("Sid", "Mike", "Jenny", "Gene", "Rajeev"); 15 | Map> result = name.stream() 16 | .collect(Collectors.groupingBy(String::length, Collectors 17 | .filtering(s-> s.contains("e"),Collectors.toList()))); 18 | 19 | System.out.println("result = " + result); 20 | System.out.println("------------------"); 21 | 22 | //instructor grouping them by Senior(>10) and Junior(<10) and filter them 23 | //on online courses 24 | Map> instructorByExpAndOnline = Instructors.getAll() 25 | .stream().collect(Collectors.groupingBy(instructor -> 26 | instructor.getYearsOfExperience()>10 ? "SENIOR": "JUNIOR", 27 | Collectors.filtering(s->s.isOnlineCourses(), 28 | Collectors.toList()))); 29 | 30 | instructorByExpAndOnline.forEach((key, value) -> { 31 | System.out.println("key = " + key + " value = " + value); 32 | }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/GroupingExample3.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.LinkedHashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.stream.Collectors; 10 | 11 | public class GroupingExample3 { 12 | public static void main(String[] args) { 13 | //grouping by length of string and also checking that the names contains e 14 | //and only return those name which has e in it 15 | List name = List.of("Sid", "Mike", "Jenny", "Gene", "Rajeev"); 16 | LinkedHashMap> result = name.stream() 17 | .collect(Collectors.groupingBy(String::length, LinkedHashMap::new, Collectors 18 | .filtering(s-> s.contains("e"),Collectors.toList()))); 19 | 20 | System.out.println("result = " + result); 21 | System.out.println("------------------"); 22 | 23 | //instructor grouping them by Senior(>10) and Junior(<10) and filter them 24 | //on online courses 25 | LinkedHashMap> instructorByExpAndOnline = Instructors.getAll() 26 | .stream().collect(Collectors.groupingBy(instructor -> 27 | instructor.getYearsOfExperience()>10 ? "SENIOR": "JUNIOR", 28 | LinkedHashMap::new, Collectors.filtering(s->s.isOnlineCourses(), 29 | Collectors.toList()))); 30 | 31 | instructorByExpAndOnline.forEach((key, value) -> { 32 | System.out.println("key = " + key + " value = " + value); 33 | }); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/GroupingMinMaxAvgExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.Comparator; 7 | import java.util.IntSummaryStatistics; 8 | import java.util.Map; 9 | import java.util.Optional; 10 | import java.util.stream.Collectors; 11 | 12 | public class GroupingMinMaxAvgExample { 13 | public static void main(String[] args) { 14 | //grouping the instructors in two sets of online course vs not online 15 | //and get the max years of experience of the instructors 16 | Map> maxInstructors = Instructors.getAll() 17 | .stream().collect(Collectors.groupingBy(Instructor::isOnlineCourses, 18 | Collectors.maxBy(Comparator.comparing 19 | (Instructor::getYearsOfExperience)))); 20 | 21 | maxInstructors.forEach((key, value) -> 22 | System.out.println("key = " + key + " value = " + value)); 23 | System.out.println("---------"); 24 | 25 | //collectingAndThen 26 | Map maxInstructors1 = Instructors.getAll() 27 | .stream().collect(Collectors.groupingBy(Instructor::isOnlineCourses, 28 | Collectors.collectingAndThen( 29 | Collectors.maxBy(Comparator.comparing 30 | (Instructor::getYearsOfExperience)), 31 | Optional::get))); 32 | 33 | maxInstructors1.forEach((key, value) -> 34 | System.out.println("key = " + key + " value = " + value)); 35 | 36 | //average years of experience of instructors who teaches online or not 37 | 38 | Map maxInstructors2 = Instructors.getAll() 39 | .stream().collect(Collectors.groupingBy(Instructor::isOnlineCourses, 40 | Collectors.averagingInt( 41 | Instructor::getYearsOfExperience) 42 | )); 43 | System.out.println("---------"); 44 | maxInstructors2.forEach((key, value) -> 45 | System.out.println("key = " + key + " value = " + value)); 46 | 47 | //drive a statistical summary from properties of grouped items 48 | 49 | Map maxInstructors3 = Instructors.getAll() 50 | .stream().collect(Collectors.groupingBy(Instructor::isOnlineCourses, 51 | Collectors.summarizingInt( 52 | Instructor::getYearsOfExperience) 53 | )); 54 | System.out.println("---------"); 55 | maxInstructors3.forEach((key, value) -> 56 | System.out.println("key = " + key + " value = " + value)); 57 | 58 | 59 | 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/IntStreamExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.Random; 4 | import java.util.stream.IntStream; 5 | 6 | public class IntStreamExample { 7 | public static void main(String[] args) { 8 | //using of 9 | IntStream numbers = IntStream.of(1,2,3,4,5); 10 | numbers.forEach(System.out::println); 11 | 12 | System.out.println("-----------"); 13 | //iterate 14 | numbers = IntStream.iterate(0, i-> i+2).limit(5); 15 | numbers.forEach(System.out::println); 16 | 17 | System.out.println("-----------"); 18 | //Random Generator 19 | numbers=IntStream.generate(new Random()::nextInt).limit(5); 20 | numbers.forEach(System.out::println); 21 | 22 | System.out.println("-----------"); 23 | //range 24 | 25 | numbers = IntStream.range(1,5); 26 | numbers.forEach(System.out::println); 27 | 28 | System.out.println("-----------"); 29 | 30 | //rangeClosed 31 | numbers = IntStream.rangeClosed(1,5); 32 | numbers.forEach(System.out::println); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/JoiningExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | public class JoiningExample { 10 | public static void main(String[] args) { 11 | String result = Stream.of("E","F", "G", "H").collect(Collectors.joining()); 12 | System.out.println(result); 13 | 14 | result = Stream.of("E","F","G","H").collect(Collectors.joining(",")); 15 | System.out.println(result); 16 | 17 | result = Stream.of ("E", "F", "G", "H").collect(Collectors. 18 | joining(",","{","}" )); 19 | System.out.println(result); 20 | 21 | //instructors names seperated by ' and prefix { and suffix } 22 | String namesConcatenated = Instructors.getAll().stream() 23 | .map(Instructor::getName) 24 | .collect(Collectors.joining(",","{", "}")); 25 | System.out.println("namesConcatenated = " + namesConcatenated); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/LongStreamExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.Random; 4 | import java.util.stream.LongStream; 5 | 6 | public class LongStreamExample { 7 | public static void main(String[] args) { 8 | //of 9 | LongStream numbers = LongStream.of(1,2,3,4,5); 10 | numbers.forEach(System.out::println); 11 | System.out.println("----------"); 12 | 13 | //iterate 14 | numbers = LongStream.iterate(0, i->i+2).limit(5); 15 | numbers.forEach(System.out::println); 16 | System.out.println("----------"); 17 | 18 | //generate 19 | numbers = LongStream.generate(new Random()::nextLong).limit(5); 20 | numbers.forEach(System.out::println); 21 | System.out.println("----------"); 22 | 23 | //range 24 | numbers= LongStream.range(1,5); 25 | numbers.forEach(System.out::println); 26 | System.out.println("----------"); 27 | 28 | //rangeClosed 29 | numbers = LongStream.rangeClosed(1,5); 30 | numbers.forEach(System.out::println); 31 | System.out.println("----------"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/MapExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.List; 7 | import java.util.Set; 8 | import java.util.stream.Collectors; 9 | 10 | public class MapExample { 11 | public static void main(String[] args) { 12 | //return only instructor names from the instructor list 13 | Set instructorNames = Instructors.getAll().stream() 14 | .map(Instructor::getName) 15 | .map(String::toUpperCase) 16 | .collect(Collectors.toSet()); 17 | System.out.println(instructorNames); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/MapToObjLongDoubleExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.ThreadLocalRandom; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.DoubleStream; 7 | import java.util.stream.IntStream; 8 | import java.util.stream.LongStream; 9 | 10 | public class MapToObjLongDoubleExample { 11 | public static void main(String[] args) { 12 | List randomIds = IntStream.rangeClosed(0,5) 13 | .mapToObj((i) -> { 14 | return new RandomIds(i, ThreadLocalRandom.current().nextInt(100)); 15 | }).collect(Collectors.toList()); 16 | 17 | randomIds.forEach(System.out::println); 18 | System.out.println("------------"); 19 | 20 | LongStream longStream = IntStream.rangeClosed(0,5).mapToLong(i -> (long)i); 21 | longStream.forEach(System.out::println); 22 | System.out.println("------------"); 23 | 24 | DoubleStream doubleStream = LongStream.rangeClosed(0,5).mapToDouble(i -> (double)i); 25 | doubleStream.forEach(System.out::println); 26 | } 27 | } 28 | 29 | class RandomIds{ 30 | int id; 31 | int randomNumbers; 32 | 33 | public RandomIds(int id, int randomNumbers) { 34 | this.id = id; 35 | this.randomNumbers = randomNumbers; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return "RandomIds{" + 41 | "id=" + id + 42 | ", randomNumbers=" + randomNumbers + 43 | '}'; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/NumericStreamAggregateExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.OptionalDouble; 4 | import java.util.OptionalInt; 5 | import java.util.stream.IntStream; 6 | import java.util.stream.LongStream; 7 | 8 | public class NumericStreamAggregateExample { 9 | public static void main(String[] args) { 10 | //sum 11 | int sum = IntStream.rangeClosed(0,1000).sum(); 12 | System.out.println("sum of 1000 numbers is: " + sum); 13 | 14 | //min 15 | OptionalInt min = IntStream.rangeClosed(0,1000).min(); 16 | if (min.isPresent()) 17 | System.out.println("Minimum of 1000 numbers is: " + min.getAsInt()); 18 | 19 | //max 20 | OptionalInt max = IntStream.rangeClosed(0,1000).max(); 21 | if (max.isPresent()) 22 | System.out.println("Max of 1000 numbers is: " + max.getAsInt()); 23 | 24 | //average 25 | OptionalDouble average = LongStream.rangeClosed(0,1000).asDoubleStream().average(); 26 | System.out.println("Average is: " + (average.isPresent() ? average.getAsDouble() 27 | : 0.0)); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/PartitioningByExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Set; 9 | import java.util.function.Predicate; 10 | import java.util.stream.Collectors; 11 | 12 | public class PartitioningByExample { 13 | public static void main(String[] args) { 14 | //partition instructors in two groups of instructor 15 | //first is years of experience is > 10 and other is <=10 16 | Predicate experiencePredicate = instructor -> 17 | instructor.getYearsOfExperience()>10; 18 | Map> partitionMap = Instructors.getAll() 19 | .stream().collect(Collectors.partitioningBy(experiencePredicate)); 20 | partitionMap.forEach((key,value)-> { 21 | System.out.println("key = " + key + " value = " + value); 22 | }); 23 | System.out.println("-------------------------------"); 24 | 25 | //partition but return is set instead of list 26 | 27 | Map> partitionSet = Instructors.getAll() 28 | .stream().collect(Collectors.partitioningBy(experiencePredicate, 29 | Collectors.toSet())); 30 | partitionSet.forEach((key,value) -> { 31 | System.out.println("key = " + key + " value: " + value); 32 | }); 33 | 34 | 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamComparatorExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.Comparator; 7 | import java.util.List; 8 | import java.util.logging.Filter; 9 | import java.util.stream.Collectors; 10 | 11 | public class StreamComparatorExample { 12 | public static void main(String[] args) { 13 | //retuning all instructors sorted by their name 14 | List list = Instructors.getAll().stream() 15 | .sorted(Comparator.comparing(Instructor::getName).reversed()) 16 | .collect(Collectors.toList()); 17 | 18 | list.forEach(System.out::println); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.function.Predicate; 9 | import java.util.stream.Collectors; 10 | 11 | public class StreamExample { 12 | public static void main(String[] args) { 13 | //creating a map of names and course of instructors who teaches 14 | //online have more than 10 years of experience 15 | 16 | Predicate p1 = (i) -> i.isOnlineCourses(); 17 | Predicate p2 = (i) -> i.getYearsOfExperience()>10; 18 | 19 | List list = Instructors.getAll(); 20 | list.stream().filter(p1).filter(p2); 21 | 22 | Map> map = list.stream() 23 | .filter(p1) 24 | .filter(p2) 25 | .peek(s-> System.out.println(s)) 26 | .collect(Collectors.toMap(Instructor::getName, Instructor::getCourses)); 27 | 28 | //System.out.println(map); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamFactoryMethodExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.Random; 4 | import java.util.stream.Stream; 5 | 6 | public class StreamFactoryMethodExample { 7 | public static void main(String[] args) { 8 | //of 9 | Stream stream = Stream.of(1,2,3,4,5,6,7,8); 10 | stream.forEach(System.out::println); 11 | 12 | System.out.println("-----------"); 13 | //iterate generate a stream of 10 even numbers 14 | Stream stream1 = Stream.iterate(0,i->i+2).limit(10); 15 | stream1.forEach(System.out::println); 16 | 17 | System.out.println("--------------"); 18 | //generate 10 random numbers 19 | Stream stream2 = Stream.generate(new Random()::nextInt).limit(10); 20 | stream2.forEach(System.out::println); 21 | 22 | 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamFindAnyAndFirstExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.Optional; 7 | 8 | public class StreamFindAnyAndFirstExample { 9 | public static void main(String[] args) { 10 | Optional instructorOptional = Instructors.getAll().stream() 11 | .findAny(); 12 | if(instructorOptional.isPresent()) 13 | System.out.println(instructorOptional.get()); 14 | 15 | instructorOptional = Instructors.getAll().stream().findFirst(); 16 | if (instructorOptional.isPresent()) 17 | System.out.println(instructorOptional.get()); 18 | 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamLimitAndSkipExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class StreamLimitAndSkipExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1,2,3,4,5,6,7,8); 10 | List limit5numbers = numbers.stream().limit(5).collect(Collectors.toList()); 11 | limit5numbers.forEach(System.out::println); 12 | 13 | System.out.println("-----"); 14 | List skip5numbers = numbers.stream().skip(5).collect(Collectors.toList()); 15 | skip5numbers.forEach(System.out::println); 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamMapFilterReduceExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | public class StreamMapFilterReduceExample { 7 | public static void main(String[] args) { 8 | //total years of experience b/w instructors 9 | int result = Instructors.getAll().stream() 10 | .filter(Instructor::isOnlineCourses) 11 | .map(Instructor::getYearsOfExperience) 12 | .reduce(0,Integer::sum); 13 | 14 | System.out.println(result); 15 | 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamMaxExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Optional; 6 | 7 | public class StreamMaxExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1,2,3,4,5,6,7,8); 10 | //max using stream max function 11 | Optional result = numbers.stream().max(Integer::compareTo); 12 | if(result.isPresent()) 13 | System.out.println(result.get()); 14 | //(0,1) - 1 // return 0 15 | //(1,2) - 2 16 | //(2,3) - 3 17 | int result2 = numbers.stream().reduce(0,(a,b)-> a>b?a:b); 18 | Optional result3 = numbers.stream().reduce((a,b)->a>b?a:b); 19 | if(result3.isPresent()) 20 | System.out.println(result3.get()); 21 | 22 | Optional result4 = numbers.stream().reduce(Integer::max); 23 | if(result4.isPresent()) 24 | System.out.println(result4.get()); 25 | 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamMinExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Optional; 6 | 7 | public class StreamMinExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1,2,3,4,5,6,7,8); 10 | //Stream min function 11 | Optional result = numbers.stream().min(Integer::compareTo); 12 | if(result.isPresent()) 13 | System.out.println(result.get()); 14 | 15 | //reduce function 16 | //(0,1) - 0 //(0,3) - 0 17 | //(0,2) - 0 18 | int result1 = numbers.stream().reduce(0,(a,b) -> a a numbers = Arrays.asList(1,2,3,4,5,6,7,8,9); 10 | int results = numbers.stream() 11 | //0 +1 = 1 //10+5= 15 //36+9=45 12 | //1 + 2 = 3 //15+ 6= 21 13 | //3 + 3 = 6 //21+7 = 28 14 | //6+ 4 = 10 //28+8 = 36 15 | .reduce(0,(a,b) -> a +b); 16 | 17 | //1 * 1 = 1 //0*1 = 0 18 | //1 * 2 = 2 //0*2=0 19 | int results1 = numbers.stream().reduce(1,(a,b) -> a* b); 20 | System.out.println(results); 21 | System.out.println(results1); 22 | 23 | Optional result2 = numbers.stream().reduce((a, b) -> a + b); 24 | System.out.println("--------"); 25 | if(result2.isPresent()) 26 | System.out.println(result2.get()); 27 | 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamReduceExample2.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructors; 4 | 5 | import java.util.Optional; 6 | 7 | public class StreamReduceExample2 { 8 | public static void main(String[] args) { 9 | //printing the instructor who has the highest years of experience 10 | Optional instructor = Instructors.getAll().stream() 11 | .reduce((s1,s2)-> s2.getYearsOfExperience() 12 | >s1.getYearsOfExperience()?s2:s1); 13 | if(instructor.isPresent()) 14 | System.out.println(instructor.get()); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamVsCollectionExample.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | public class StreamVsCollectionExample { 9 | public static void main(String[] args) { 10 | List names = new ArrayList<>(); 11 | names.add("Mike"); 12 | names.add("Syed"); 13 | names.add("Rajeev"); 14 | System.out.println("--------"); 15 | System.out.println(names); 16 | 17 | names.remove("Syed"); 18 | System.out.println("--------"); 19 | System.out.println(names); 20 | 21 | for (String name:names){ 22 | System.out.println(name); 23 | } 24 | System.out.println("--------"); 25 | for (String name:names){ 26 | System.out.println(name); 27 | } 28 | System.out.println("--------"); 29 | for (String name:names){ 30 | System.out.println(name); 31 | } 32 | 33 | 34 | 35 | Stream namesStream = names.stream(); 36 | System.out.println("--------"); 37 | namesStream.forEach(System.out::println); 38 | System.out.println("--------"); 39 | List list2 = names.stream().filter(s->s.startsWith("M")).collect(Collectors.toList()); 40 | System.out.println(list2); 41 | 42 | 43 | 44 | 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/com/modernjava/streams/StreamsOperations.java: -------------------------------------------------------------------------------- 1 | package com.modernjava.streams; 2 | 3 | import com.modernjava.funcprogramming.Instructor; 4 | import com.modernjava.funcprogramming.Instructors; 5 | 6 | import java.util.List; 7 | import java.util.Optional; 8 | import java.util.Set; 9 | import java.util.stream.Collectors; 10 | 11 | public class StreamsOperations { 12 | public static void main(String[] args) { 13 | //count distinct 14 | Long count = Instructors.getAll().stream() 15 | .map(Instructor::getCourses) 16 | .flatMap(List::stream) 17 | .distinct() 18 | .count(); 19 | 20 | System.out.println(count); 21 | //distinct 22 | List courses = Instructors.getAll().stream() 23 | .map(Instructor::getCourses) 24 | .flatMap(List::stream) 25 | .distinct() 26 | .sorted() 27 | .collect(Collectors.toList()); 28 | System.out.println(courses); 29 | 30 | //anymatch, allmatch and nonmatch 31 | 32 | 33 | boolean match = Instructors.getAll().stream() 34 | .map(Instructor::getCourses) 35 | .flatMap(List::stream) 36 | .noneMatch(s -> s.startsWith("J")); 37 | 38 | System.out.println(match); 39 | 40 | 41 | 42 | 43 | } 44 | } 45 | --------------------------------------------------------------------------------