Skip to content

Commit

Permalink
Add notes and examples
Browse files Browse the repository at this point in the history
  • Loading branch information
abhinav-nath committed May 10, 2022
1 parent e2f3253 commit 564dadc
Show file tree
Hide file tree
Showing 150 changed files with 5,247 additions and 1 deletion.
34 changes: 34 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = false
trim_trailing_whitespace = true
max_line_length = 200
tab_width = 4

[*.java]
# don't use wildcard for Java imports
wildcard_import_limit = 999
ij_visual_guides = 120
ij_wrap_on_typing = true
ij_java_binary_operation_sign_on_next_line = true
ij_java_align_multiline_chained_methods = true
ij_java_align_multiline_ternary_operation = true
ij_java_align_multiline_array_initializer_expression = true
ij_java_use_single_class_imports = true
ij_java_class_count_to_use_import_on_demand = 999
ij_java_names_count_to_use_import_on_demand = 999
ij_java_imports_layout = *, |, java.**, |, javax.**, |, io.**, |, org.**, |, lombok.**, |, com.**, |, $*
ij_java_layout_static_imports_separately = true

[*.xml]
indent_size = 4
ij_xml_tab_width = 4

# Shell scripts
[*.{cmd, bat}]
end_of_line = crlf
28 changes: 28 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Compiled class file
*.class
classes

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
/bin/

.idea
/out/
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
# all-about-java-8
# all-about-java-8

Detailed explanations and code examples of most of the new features introduced by Java 8.
11 changes: 11 additions & 0 deletions all-about-java-8.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
10 changes: 10 additions & 0 deletions src/com/codecafe/java8/codingstyles/ImperativeVsDeclarative.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
+ Imperative style has accidental complexity.

+ Functional Style has less complexity and is EASIER to parallelize.

+ Parallelism is a really difficult and complex job in Imperative style. It makes your life like hell.

+ It can be quoted as --> "Synchronize and Suffer model".

+ As you try to squeeze out performance by parallelizing in functional style, the code becomes more and more complex and difficult to understand/maintain.

27 changes: 27 additions & 0 deletions src/com/codecafe/java8/codingstyles/ImperativeVsDeclarative1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.codecafe.java8.codingstyles;

import java.util.stream.IntStream;

public class ImperativeVsDeclarative1 {

public static void main(String[] args) {

// Find sum of Integers from 0 to 100

/* Imperative Approach -- how to achieve the result ? */

int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}

System.out.println("Sum with Imperative approach : " + sum);

/* Declarative Approach -- What result to achieve ? */
/* Need not to care about how it is done behind the scenes */
int sum1 = IntStream.rangeClosed(0, 100).sum();

System.out.println("Sum with Declarative approach : " + sum1);
}

}
37 changes: 37 additions & 0 deletions src/com/codecafe/java8/codingstyles/ImperativeVsDeclarative2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.codecafe.java8.codingstyles;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ImperativeVsDeclarative2 {

public static void main(String[] args) {

// Remove duplicates from a list of Integers

/* Imperative Approach -- how to achieve the result ? */

List<Integer> integerList = Arrays.asList(1, 2, 3, 3, 4, 5, 3, 4, 1, 6, 7, 6, 8, 9, 2, 8, 10, 10, 2, 3, 4, 1, 1, 1);

List<Integer> uniqueList = new ArrayList<>();

for (Integer integer : integerList) {
if (!uniqueList.contains(integer)) {
uniqueList.add(integer);
}
}

System.out.println("Unique List with Imperative approach : " + uniqueList);

/* Declarative Approach -- What result to achieve ? */

List<Integer> uniqueList1 = integerList.stream()
.distinct()
.collect(Collectors.toList());

System.out.println("Unique List with Imperative approach : " + uniqueList1);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.codecafe.java8.completablefuture;

import java.util.concurrent.CompletableFuture;

public class CompletableFuturesAreImmortal {

public static CompletableFuture<Integer> create() {
return CompletableFuture.supplyAsync(() -> 2);
}

public static void main(String[] args) {

create().thenAccept(data -> System.out.println(data)) // this returns void CompletableFuture
.thenRun(() -> System.out.println("This never dies")) // Runnable
.thenRun(() -> System.out.println("Really, this never dies"))
.thenRun(() -> System.out.println("Really, really, this never dies"));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.codecafe.java8.completablefuture;

import java.util.concurrent.CompletableFuture;

public class CompletableFuturesBasicDemo {

public static CompletableFuture<Integer> create() {
return CompletableFuture.supplyAsync(() -> 2);
}

public static void main(String[] args) {
CompletableFuture<Integer> future = create();

// this is how to translate it
// I have a future object, when the future resolves, then accept the result given by it
future.thenAccept(data -> System.out.println(data));
}

}
22 changes: 22 additions & 0 deletions src/com/codecafe/java8/datetime/CompareTwoInstants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.codecafe.java8.datetime;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class CompareTwoInstants {

public static void main(String[] args) {
Instant now = Instant.now();
Instant aWeekBefore = now.minus(7, ChronoUnit.DAYS);

System.out.println("---------------------------------------------");
System.out.println("Now : " + now);
System.out.println("A week before : " + aWeekBefore);
System.out.println("---------------------------------------------");
System.out.println("now.compareTo(aWeekBefore) = " + now.compareTo(aWeekBefore));
System.out.println("aWeekBefore.compareTo(aWeekBefore) = " + aWeekBefore.compareTo(aWeekBefore));
System.out.println("aWeekBefore.compareTo(now) = " + aWeekBefore.compareTo(now));
System.out.println("---------------------------------------------");
}

}
30 changes: 30 additions & 0 deletions src/com/codecafe/java8/datetime/FindDaysBetweenTwoDates.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.codecafe.java8.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class FindDaysBetweenTwoDates {

public static void main(String[] args) {
LocalDate date1 = LocalDate.of(1990, Month.AUGUST, 26);

LocalDate date2 = LocalDate.now();

long numberOfDaysBetween = ChronoUnit.DAYS.between(date1, date2);

System.out.println("Number of days between " + date1 + " and " + date2 + " = " + numberOfDaysBetween);

String dateBeforeString = "2021-05-31";
String dateAfterString = "2021-06-09";

// parse the dates
LocalDate dateBefore = LocalDate.parse(dateBeforeString);
LocalDate dateAfter = LocalDate.parse(dateAfterString);

numberOfDaysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);

System.out.println("Number of days between " + dateBefore + " and " + dateAfter + " = " + numberOfDaysBetween);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.codecafe.java8.datetime;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

public class MeasureElapsedTimeUsingInstant {

public static void main(String[] args) {
Instant start = Instant.now();

// Measure execution time for this method
methodToTime();

Instant finish = Instant.now();

long timeElapsedInNanos = Duration.between(start, finish).toNanos(); // in nanos
long timeElapsedInMillis = Duration.between(start, finish).toMillis(); // in millis

System.out.println("elapsed time : " + timeElapsedInNanos + " nanos" + ", " + timeElapsedInMillis + " millis");
}

private static void methodToTime() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.codecafe.java8.datetime;

import java.util.concurrent.TimeUnit;

// Recommended method

public class MeasureElapsedTimeUsingNanoTime {

public static void main(String[] args) {
long startTime = System.nanoTime();

// Measure execution time for this method
methodToTime();

long endTime = System.nanoTime();

long timeElapsedInNanos = (endTime - startTime); // in nanos
long timeElapsedInMillis = TimeUnit.NANOSECONDS.toMillis(timeElapsedInNanos); // in millis

System.out.println("elapsed time : " + timeElapsedInNanos + " nanos" + ", " + timeElapsedInMillis + " millis");
}

private static void methodToTime() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
19 changes: 19 additions & 0 deletions src/com/codecafe/java8/datetime/NumberOfDaysUntil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.codecafe.java8.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class NumberOfDaysUntil {

public static void main(String[] args) {
LocalDate from = LocalDate.now();

LocalDate until = LocalDate.of(2021, Month.JUNE, 30);

long daysUntil = from.until(until, ChronoUnit.DAYS);

System.out.println("Days until " + until + " = " + daysUntil);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.codecafe.java8.functionalinterfaces;

import java.util.Comparator;

public class ComparatorLambdaExample {

public static void main(String args[]) {

// prior to Java 8
Comparator<Integer> comparator = new Comparator<Integer>() {

@Override
public int compare(Integer arg0, Integer arg1) {
return arg0.compareTo(arg1);
}
};

System.out.println("Result with legacy Comparator : " + comparator.compare(3, 2));

// Java 8 Lambda Syntax
Comparator<Integer> comparatorLambda = (Integer a, Integer b) -> {
return a.compareTo(b);
};

System.out.println("Result with Lambda 1 : " + comparatorLambda.compare(3, 2));

// Java 8 Lambda Syntax -- no need to write in curly braces
Comparator<Integer> comparatorLambda1 = (Integer a, Integer b) -> a.compareTo(b);

System.out.println("Result with Lambda 2 : " + comparatorLambda1.compare(3, 2));

// Java 8 Lambda Syntax -- no need to define the type of a and b
Comparator<Integer> comparatorLambda2 = (a, b) -> {
return a.compareTo(b);
};

System.out.println("Result with Lambda 3 : " + comparatorLambda2.compare(3, 2));
}

}
Loading

0 comments on commit 564dadc

Please sign in to comment.