Collapse core-java-8 into core-java
This commit is contained in:
@@ -24,4 +24,19 @@
|
||||
- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
|
||||
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
|
||||
- [Random List Element](http://www.baeldung.com/java-random-list-element)
|
||||
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
||||
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
||||
|
||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
||||
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
|
||||
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
|
||||
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
|
||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
||||
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
|
||||
- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
||||
- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams)
|
||||
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
|
||||
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||
13
core-java/src/main/java/com/baeldung/.gitignore
vendored
Normal file
13
core-java/src/main/java/com/baeldung/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
12
core-java/src/main/java/com/baeldung/Adder.java
Normal file
12
core-java/src/main/java/com/baeldung/Adder.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.baeldung;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface Adder {
|
||||
|
||||
String addWithFunction(Function<String, String> f);
|
||||
|
||||
void addWithConsumer(Consumer<Integer> f);
|
||||
|
||||
}
|
||||
17
core-java/src/main/java/com/baeldung/AdderImpl.java
Normal file
17
core-java/src/main/java/com/baeldung/AdderImpl.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package com.baeldung;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class AdderImpl implements Adder {
|
||||
|
||||
@Override
|
||||
public String addWithFunction(final Function<String, String> f) {
|
||||
return f.apply("Something ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addWithConsumer(final Consumer<Integer> f) {
|
||||
}
|
||||
|
||||
}
|
||||
12
core-java/src/main/java/com/baeldung/Bar.java
Normal file
12
core-java/src/main/java/com/baeldung/Bar.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Bar {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Bar";
|
||||
}
|
||||
|
||||
}
|
||||
11
core-java/src/main/java/com/baeldung/Baz.java
Normal file
11
core-java/src/main/java/com/baeldung/Baz.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Baz {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Baz";
|
||||
}
|
||||
}
|
||||
10
core-java/src/main/java/com/baeldung/Foo.java
Normal file
10
core-java/src/main/java/com/baeldung/Foo.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Foo {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default void defaultMethod() {
|
||||
}
|
||||
}
|
||||
11
core-java/src/main/java/com/baeldung/FooExtended.java
Normal file
11
core-java/src/main/java/com/baeldung/FooExtended.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.baeldung;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface FooExtended extends Baz, Bar {
|
||||
|
||||
@Override
|
||||
default String defaultMethod() {
|
||||
return Bar.super.defaultMethod();
|
||||
}
|
||||
|
||||
}
|
||||
37
core-java/src/main/java/com/baeldung/UseFoo.java
Normal file
37
core-java/src/main/java/com/baeldung/UseFoo.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.baeldung;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class UseFoo {
|
||||
|
||||
private String value = "Enclosing scope value";
|
||||
|
||||
public String add(final String string, final Foo foo) {
|
||||
return foo.method(string);
|
||||
}
|
||||
|
||||
public String addWithStandardFI(final String string, final Function<String, String> fn) {
|
||||
return fn.apply(string);
|
||||
}
|
||||
|
||||
public String scopeExperiment() {
|
||||
final Foo fooIC = new Foo() {
|
||||
String value = "Inner class value";
|
||||
|
||||
@Override
|
||||
public String method(final String string) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
final String resultIC = fooIC.method("");
|
||||
|
||||
final Foo fooLambda = parameter -> {
|
||||
final String value = "Lambda value";
|
||||
return this.value;
|
||||
};
|
||||
final String resultLambda = fooLambda.method("");
|
||||
|
||||
return "Results: resultIC = " + resultIC + ", resultLambda = " + resultLambda;
|
||||
}
|
||||
|
||||
}
|
||||
2
core-java/src/main/java/com/baeldung/datetime/README.md
Normal file
2
core-java/src/main/java/com/baeldung/datetime/README.md
Normal file
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Period;
|
||||
|
||||
public class UseDuration {
|
||||
|
||||
public LocalTime modifyDates(LocalTime localTime,Duration duration){
|
||||
return localTime.plus(duration);
|
||||
}
|
||||
|
||||
public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
|
||||
return Duration.between(localTime1, localTime2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
public class UseLocalDate {
|
||||
|
||||
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
|
||||
return LocalDate.of(year, month, dayOfMonth);
|
||||
}
|
||||
|
||||
public LocalDate getLocalDateUsingParseMethod(String representation){
|
||||
return LocalDate.parse(representation);
|
||||
}
|
||||
|
||||
public LocalDate getLocalDateFromClock(){
|
||||
LocalDate localDate = LocalDate.now();
|
||||
return localDate;
|
||||
}
|
||||
|
||||
public LocalDate getNextDay(LocalDate localDate){
|
||||
return localDate.plusDays(1);
|
||||
}
|
||||
|
||||
public LocalDate getPreviousDay(LocalDate localDate){
|
||||
return localDate.minus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
|
||||
public DayOfWeek getDayOfWeek(LocalDate localDate){
|
||||
DayOfWeek day = localDate.getDayOfWeek();
|
||||
return day;
|
||||
}
|
||||
|
||||
public LocalDate getFirstDayOfMonth(){
|
||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||
return firstDayOfMonth;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartOfDay(LocalDate localDate){
|
||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||
return startofDay;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class UseLocalDateTime {
|
||||
|
||||
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
|
||||
return LocalDateTime.parse(representation);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class UseLocalTime {
|
||||
|
||||
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
|
||||
LocalTime localTime = LocalTime.of(hour, min, seconds);
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
|
||||
LocalTime localTime = LocalTime.parse(timeRepresentation);
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeFromClock(){
|
||||
LocalTime localTime = LocalTime.now();
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public LocalTime addAnHour(LocalTime localTime){
|
||||
LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
|
||||
return newTime;
|
||||
}
|
||||
|
||||
public int getHourFromLocalTime(LocalTime localTime){
|
||||
return localTime.getHour();
|
||||
}
|
||||
|
||||
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
|
||||
return localTime.withMinute(minute);
|
||||
}
|
||||
}
|
||||
15
core-java/src/main/java/com/baeldung/datetime/UsePeriod.java
Normal file
15
core-java/src/main/java/com/baeldung/datetime/UsePeriod.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
public class UsePeriod {
|
||||
|
||||
public LocalDate modifyDates(LocalDate localDate,Period period){
|
||||
return localDate.plus(period);
|
||||
}
|
||||
|
||||
public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
|
||||
return Period.between(localDate1, localDate2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class UseToInstant {
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Date date){
|
||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
|
||||
return localDateTime;
|
||||
}
|
||||
|
||||
public LocalDateTime convertDateToLocalDate(Calendar calendar){
|
||||
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
|
||||
return localDateTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class UseZonedDateTime {
|
||||
|
||||
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
|
||||
return zonedDateTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
public class Computer {
|
||||
|
||||
private Integer age;
|
||||
private String color;
|
||||
private Integer healty;
|
||||
|
||||
public Computer(final int age, final String color) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Computer(final Integer age, final String color, final Integer healty) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public Computer() {
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(final Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(final String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Integer getHealty() {
|
||||
return healty;
|
||||
}
|
||||
|
||||
public void setHealty(final Integer healty) {
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public void turnOnPc() {
|
||||
System.out.println("Computer turned on");
|
||||
}
|
||||
|
||||
public void turnOffPc() {
|
||||
System.out.println("Computer turned off");
|
||||
}
|
||||
|
||||
public Double calculateValue(Double initialValue) {
|
||||
return initialValue / 1.50;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Computer{" + "age=" + age + ", color='" + color + '\'' + ", healty=" + healty + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Computer computer = (Computer) o;
|
||||
|
||||
if (age != null ? !age.equals(computer.age) : computer.age != null) {
|
||||
return false;
|
||||
}
|
||||
return color != null ? color.equals(computer.color) : computer.color == null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = age != null ? age.hashCode() : 0;
|
||||
result = 31 * result + (color != null ? color.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import com.baeldung.doublecolon.function.ComputerPredicate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ComputerUtils {
|
||||
|
||||
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
|
||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||
|
||||
final List<Computer> result = new ArrayList<>();
|
||||
inventory.stream().filter(p::filter).forEach(result::add);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void repair(final Computer computer) {
|
||||
if (computer.getHealty() < 50) {
|
||||
computer.setHealty(100);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class MacbookPro extends Computer {
|
||||
|
||||
public MacbookPro(int age, String color) {
|
||||
super(age, color);
|
||||
}
|
||||
|
||||
public MacbookPro(Integer age, String color, Integer healty) {
|
||||
super(age, color, healty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOnPc() {
|
||||
System.out.println("MacbookPro turned on");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOffPc() {
|
||||
System.out.println("MacbookPro turned off");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Double calculateValue(Double initialValue) {
|
||||
|
||||
Function<Double, Double> function = super::calculateValue;
|
||||
final Double pcValue = function.apply(initialValue);
|
||||
System.out.println("First value is:" + pcValue);
|
||||
return pcValue + (initialValue / 10);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import com.baeldung.doublecolon.Computer;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ComputerPredicate {
|
||||
|
||||
boolean filter(Computer c);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface TriFunction<A, B, C, R> {
|
||||
|
||||
R apply(A a, B b, C c);
|
||||
|
||||
default <V> TriFunction<A, B, C, V> andThen(final Function<? super R, ? extends V> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final A a, final B b, final C c) -> after.apply(apply(a, b, c));
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,5 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.commons.collections15.Predicate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
@@ -13,13 +7,12 @@ import java.util.stream.Collectors;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private static EnumSet<PizzaStatus> undeliveredPizzaStatuses =
|
||||
EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
|
||||
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses =
|
||||
EnumSet.of(PizzaStatusEnum.DELIVERED);
|
||||
|
||||
private PizzaStatus status;
|
||||
private PizzaStatusEnum status;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
||||
public enum PizzaStatus {
|
||||
public enum PizzaStatusEnum {
|
||||
ORDERED(5) {
|
||||
@Override
|
||||
public boolean isOrdered() {
|
||||
@@ -53,21 +46,20 @@ public class Pizza {
|
||||
return false;
|
||||
}
|
||||
|
||||
@JsonProperty("timeToDelivery")
|
||||
public int getTimeToDelivery() {
|
||||
return timeToDelivery;
|
||||
}
|
||||
|
||||
PizzaStatus(int timeToDelivery) {
|
||||
PizzaStatusEnum(int timeToDelivery) {
|
||||
this.timeToDelivery = timeToDelivery;
|
||||
}
|
||||
}
|
||||
|
||||
public PizzaStatus getStatus() {
|
||||
public PizzaStatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(PizzaStatus status) {
|
||||
public void setStatus(PizzaStatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@@ -80,31 +72,20 @@ public class Pizza {
|
||||
}
|
||||
|
||||
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
|
||||
return input.stream().filter(
|
||||
(s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
|
||||
.collect(Collectors.toList());
|
||||
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static EnumMap<PizzaStatus, List<Pizza>>
|
||||
groupPizzaByStatus(List<Pizza> pzList) {
|
||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
||||
return pzList.stream().collect(
|
||||
Collectors.groupingBy(Pizza::getStatus,
|
||||
() -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));
|
||||
() -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
||||
}
|
||||
|
||||
public void deliver() {
|
||||
if (isDeliverable()) {
|
||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
||||
this.setStatus(PizzaStatus.DELIVERED);
|
||||
this.setStatus(PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getJsonString(Pizza pz) throws IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz);
|
||||
}
|
||||
|
||||
private static Predicate<Pizza> thatAreNotDelivered() {
|
||||
return entry -> undeliveredPizzaStatuses.contains(entry.getStatus());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
|
||||
public enum PizzaDeliverySystemConfiguration {
|
||||
INSTANCE;
|
||||
|
||||
|
||||
2
core-java/src/main/java/com/baeldung/enums/README.md
Normal file
2
core-java/src/main/java/com/baeldung/enums/README.md
Normal file
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.forkjoin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveAction;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class CustomRecursiveAction extends RecursiveAction {
|
||||
|
||||
private String workLoad = "";
|
||||
private static final int THRESHOLD = 4;
|
||||
|
||||
private static Logger logger = Logger.getAnonymousLogger();
|
||||
|
||||
public CustomRecursiveAction(String workLoad) {
|
||||
this.workLoad = workLoad;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void compute() {
|
||||
|
||||
if (workLoad.length() > THRESHOLD) {
|
||||
ForkJoinTask.invokeAll(createSubtasks());
|
||||
} else {
|
||||
processing(workLoad);
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<CustomRecursiveAction> createSubtasks() {
|
||||
|
||||
List<CustomRecursiveAction> subtasks =
|
||||
new ArrayList<>();
|
||||
|
||||
String partOne = workLoad.substring(0, workLoad.length() / 2);
|
||||
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
|
||||
|
||||
subtasks.add(new CustomRecursiveAction(partOne));
|
||||
subtasks.add(new CustomRecursiveAction(partTwo));
|
||||
|
||||
return subtasks;
|
||||
}
|
||||
|
||||
private void processing(String work) {
|
||||
String result = work.toUpperCase();
|
||||
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.forkjoin;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveTask;
|
||||
|
||||
public class CustomRecursiveTask extends RecursiveTask<Integer> {
|
||||
|
||||
private int[] arr;
|
||||
|
||||
private static final int THRESHOLD = 20;
|
||||
|
||||
public CustomRecursiveTask(int[] arr) {
|
||||
this.arr = arr;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer compute() {
|
||||
|
||||
if (arr.length > THRESHOLD) {
|
||||
|
||||
return ForkJoinTask.invokeAll(createSubtasks())
|
||||
.stream()
|
||||
.mapToInt(ForkJoinTask::join)
|
||||
.sum();
|
||||
|
||||
} else {
|
||||
return processing(arr);
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<CustomRecursiveTask> createSubtasks() {
|
||||
List<CustomRecursiveTask> dividedTasks = new ArrayList<>();
|
||||
dividedTasks.add(new CustomRecursiveTask(
|
||||
Arrays.copyOfRange(arr, 0, arr.length / 2)));
|
||||
dividedTasks.add(new CustomRecursiveTask(
|
||||
Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
|
||||
return dividedTasks;
|
||||
}
|
||||
|
||||
private Integer processing(int[] arr) {
|
||||
return Arrays.stream(arr)
|
||||
.filter(a -> a > 10 && a < 27)
|
||||
.map(a -> a * 10)
|
||||
.sum();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.forkjoin.util;
|
||||
|
||||
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
|
||||
public class PoolUtil {
|
||||
|
||||
public static ForkJoinPool forkJoinPool = new ForkJoinPool(2);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String street;
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class CustomException extends RuntimeException {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Detail {
|
||||
|
||||
private static final List<String> PARTS = Arrays.asList("turbine", "pump");
|
||||
|
||||
public List<String> getParts() {
|
||||
return PARTS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalAddress {
|
||||
|
||||
private String street;
|
||||
|
||||
public Optional<String> getStreet() {
|
||||
return Optional.ofNullable(street);
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalUser {
|
||||
|
||||
private OptionalAddress address;
|
||||
|
||||
public Optional<OptionalAddress> getAddress() {
|
||||
return Optional.of(address);
|
||||
}
|
||||
|
||||
public void setAddress(OptionalAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
|
||||
private Address address;
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static boolean isRealUser(User user) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getOrThrow() {
|
||||
String value = null;
|
||||
Optional<String> valueOpt = Optional.ofNullable(value);
|
||||
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isLegalName(String name) {
|
||||
return name.length() > 3 && name.length() < 16;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public interface Vehicle {
|
||||
|
||||
void moveTo(long altitude, long longitude);
|
||||
|
||||
static String producer() {
|
||||
return "N&F Vehicles";
|
||||
}
|
||||
|
||||
default long[] startPosition() {
|
||||
return new long[]{23, 15};
|
||||
}
|
||||
|
||||
default String getOverview() {
|
||||
return "ATV made by " + producer();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class VehicleImpl implements Vehicle {
|
||||
|
||||
@Override
|
||||
public void moveTo(long altitude, long longitude) {
|
||||
//do nothing
|
||||
}
|
||||
}
|
||||
51
core-java/src/main/java/com/baeldung/streamApi/Product.java
Normal file
51
core-java/src/main/java/com/baeldung/streamApi/Product.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.streamApi;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Created by Alex Vengr
|
||||
*/
|
||||
public class Product {
|
||||
|
||||
private int price;
|
||||
|
||||
private String name;
|
||||
|
||||
private boolean utilize;
|
||||
|
||||
public Product(int price, String name) {
|
||||
this(price);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Product(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Product() {
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public static Stream<String> streamOf(List<String> list) {
|
||||
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.RecursiveTask;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class CountingTask extends RecursiveTask<Integer> {
|
||||
|
||||
private final TreeNode node;
|
||||
|
||||
public CountingTask(TreeNode node) {
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer compute() {
|
||||
return node.value + node.children.stream()
|
||||
.map(childNode -> new CountingTask(childNode).fork())
|
||||
.collect(Collectors.summingInt(ForkJoinTask::join));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.google.common.util.concurrent.MoreExecutors;
|
||||
|
||||
/**
|
||||
* This class demonstrates the usage of Guava's exiting executor services that keep the VM from hanging.
|
||||
* Without the exiting executor service, the task would hang indefinitely.
|
||||
* This behaviour cannot be demonstrated in JUnit tests, as JUnit kills the VM after the tests.
|
||||
*/
|
||||
public class ExitingExecutorServiceExample {
|
||||
|
||||
public static void main(String... args) {
|
||||
|
||||
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
|
||||
ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
|
||||
|
||||
executorService.submit(() -> {
|
||||
while (true) {
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.threadpool;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
public class TreeNode {
|
||||
|
||||
int value;
|
||||
|
||||
Set<TreeNode> children;
|
||||
|
||||
public TreeNode(int value, TreeNode... children) {
|
||||
this.value = value;
|
||||
this.children = Sets.newHashSet(children);
|
||||
}
|
||||
|
||||
}
|
||||
30
core-java/src/main/java/com/baeldung/unzip/UnzipFile.java
Normal file
30
core-java/src/main/java/com/baeldung/unzip/UnzipFile.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.unzip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
public class UnzipFile {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String fileZip = "src/main/resources/compressed.zip";
|
||||
final byte[] buffer = new byte[1024];
|
||||
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
|
||||
ZipEntry zipEntry = zis.getNextEntry();
|
||||
while (zipEntry != null) {
|
||||
final String fileName = zipEntry.getName();
|
||||
final File newFile = new File("src/main/resources/unzipTest/" + fileName);
|
||||
final FileOutputStream fos = new FileOutputStream(newFile);
|
||||
int len;
|
||||
while ((len = zis.read(buffer)) > 0) {
|
||||
fos.write(buffer, 0, len);
|
||||
}
|
||||
fos.close();
|
||||
zipEntry = zis.getNextEntry();
|
||||
}
|
||||
zis.closeEntry();
|
||||
zis.close();
|
||||
}
|
||||
}
|
||||
43
core-java/src/main/java/com/baeldung/zip/ZipDirectory.java
Normal file
43
core-java/src/main/java/com/baeldung/zip/ZipDirectory.java
Normal file
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipDirectory {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String sourceFile = "src/main/resources/zipTest";
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
final File fileToZip = new File(sourceFile);
|
||||
|
||||
zipFile(fileToZip, fileToZip.getName(), zipOut);
|
||||
zipOut.close();
|
||||
fos.close();
|
||||
}
|
||||
|
||||
private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException {
|
||||
if (fileToZip.isHidden()) {
|
||||
return;
|
||||
}
|
||||
if (fileToZip.isDirectory()) {
|
||||
final File[] children = fileToZip.listFiles();
|
||||
for (final File childFile : children) {
|
||||
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
|
||||
}
|
||||
return;
|
||||
}
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileName);
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
fis.close();
|
||||
}
|
||||
}
|
||||
28
core-java/src/main/java/com/baeldung/zip/ZipFile.java
Normal file
28
core-java/src/main/java/com/baeldung/zip/ZipFile.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipFile {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String sourceFile = "src/main/resources/zipTest/test1.txt";
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
final File fileToZip = new File(sourceFile);
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
zipOut.close();
|
||||
fis.close();
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipMultipleFiles {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final List<String> srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt");
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
for (final String srcFile : srcFiles) {
|
||||
final File fileToZip = new File(srcFile);
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
fis.close();
|
||||
}
|
||||
zipOut.close();
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
BIN
core-java/src/main/resources/dirCompressed.zip
Normal file
BIN
core-java/src/main/resources/dirCompressed.zip
Normal file
Binary file not shown.
BIN
core-java/src/main/resources/multiCompressed.zip
Normal file
BIN
core-java/src/main/resources/multiCompressed.zip
Normal file
Binary file not shown.
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.dateapi;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class ConversionExample {
|
||||
public static void main(String[] args) {
|
||||
Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
|
||||
ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();
|
||||
Date dateFromInstant = Date.from(Instant.now());
|
||||
GregorianCalendar calendarFromZonedDateTime = GregorianCalendar.from(ZonedDateTime.now());
|
||||
Instant instantFromDate = new Date().toInstant();
|
||||
ZoneId zoneIdFromTimeZone = TimeZone.getTimeZone("PST").toZoneId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.dateapi;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
import java.time.YearMonth;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JavaUtilTimeTest {
|
||||
|
||||
@Test
|
||||
public void currentTime() {
|
||||
final LocalDate now = LocalDate.now();
|
||||
|
||||
System.out.println(now);
|
||||
// there is not much to test here
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificTime() {
|
||||
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
|
||||
|
||||
System.out.println(birthDay);
|
||||
// there is not much to test here
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractMonth() {
|
||||
Month month = LocalDate.of(1990, Month.DECEMBER, 15).getMonth();
|
||||
|
||||
assertThat(month).isEqualTo(Month.DECEMBER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subtractTime() {
|
||||
LocalDateTime fiveHoursBefore = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).minusHours(5);
|
||||
|
||||
assertThat(fiveHoursBefore.getHour()).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void alterField() {
|
||||
LocalDateTime inJune = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).with(Month.JUNE);
|
||||
|
||||
assertThat(inJune.getMonth()).isEqualTo(Month.JUNE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void truncate() {
|
||||
LocalTime truncated = LocalTime.of(15, 12, 34).truncatedTo(ChronoUnit.HOURS);
|
||||
|
||||
assertThat(truncated).isEqualTo(LocalTime.of(15, 0, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTimeSpan() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime hourLater = now.plusHours(1);
|
||||
Duration span = Duration.between(now, hourLater);
|
||||
|
||||
assertThat(span).isEqualTo(Duration.ofHours(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void formatAndParse() throws ParseException {
|
||||
LocalDate someDate = LocalDate.of(2016, 12, 7);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
String formattedDate = someDate.format(formatter);
|
||||
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
|
||||
|
||||
assertThat(formattedDate).isEqualTo("2016-12-07");
|
||||
assertThat(parsedDate).isEqualTo(someDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void daysInMonth() {
|
||||
int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
|
||||
|
||||
assertThat(daysInMonth).isEqualTo(28);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user