Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
@@ -2,7 +2,6 @@ package com.baeldung.datetime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Period;
|
||||
|
||||
public class UseDuration {
|
||||
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.application;
|
||||
|
||||
import com.baeldung.defaultstaticinterfacemethods.model.Car;
|
||||
import com.baeldung.defaultstaticinterfacemethods.model.Vehicle;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Vehicle car = new Car("BMW");
|
||||
System.out.println(car.getBrand());
|
||||
System.out.println(car.speedUp());
|
||||
System.out.println(car.slowDown());
|
||||
System.out.println(car.turnAlarmOn());
|
||||
System.out.println(car.turnAlarmOff());
|
||||
System.out.println(Vehicle.getHorsePower(2500, 480));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public interface Alarm {
|
||||
|
||||
default String turnAlarmOn() {
|
||||
return "Turning the alarm on.";
|
||||
}
|
||||
|
||||
default String turnAlarmOff() {
|
||||
return "Turning the alarm off.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public class Car implements Vehicle {
|
||||
|
||||
private final String brand;
|
||||
|
||||
public Car(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String speedUp() {
|
||||
return "The car is speeding up.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String slowDown() {
|
||||
return "The car is slowing down.";
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public class Motorbike implements Vehicle {
|
||||
|
||||
private final String brand;
|
||||
|
||||
public Motorbike(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String speedUp() {
|
||||
return "The motorbike is speeding up.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String slowDown() {
|
||||
return "The motorbike is slowing down.";
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public class MultiAlarmCar implements Vehicle, Alarm {
|
||||
|
||||
private final String brand;
|
||||
|
||||
public MultiAlarmCar(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String speedUp() {
|
||||
return "The motorbike is speeding up.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String slowDown() {
|
||||
return "The mootorbike is slowing down.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String turnAlarmOn() {
|
||||
return Vehicle.super.turnAlarmOn() + " " + Alarm.super.turnAlarmOn();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String turnAlarmOff() {
|
||||
return Vehicle.super.turnAlarmOff() + " " + Alarm.super.turnAlarmOff();
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public interface Vehicle {
|
||||
|
||||
String getBrand();
|
||||
|
||||
String speedUp();
|
||||
|
||||
String slowDown();
|
||||
|
||||
default String turnAlarmOn() {
|
||||
return "Turning the vehice alarm on.";
|
||||
}
|
||||
|
||||
default String turnAlarmOff() {
|
||||
return "Turning the vehicle alarm off.";
|
||||
}
|
||||
|
||||
static int getHorsePower(int rpm, int torque) {
|
||||
return (rpm * torque) / 5252;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.iterators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Source code https://github.com/eugenp/tutorials
|
||||
*
|
||||
* @author Santosh Thakur
|
||||
*/
|
||||
|
||||
public class Iterators {
|
||||
|
||||
public static int failFast1() {
|
||||
ArrayList<Integer> numbers = new ArrayList<>();
|
||||
|
||||
numbers.add(10);
|
||||
numbers.add(20);
|
||||
numbers.add(30);
|
||||
numbers.add(40);
|
||||
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Integer number = iterator.next();
|
||||
numbers.add(50);
|
||||
}
|
||||
|
||||
return numbers.size();
|
||||
}
|
||||
|
||||
public static int failFast2() {
|
||||
ArrayList<Integer> numbers = new ArrayList<>();
|
||||
numbers.add(10);
|
||||
numbers.add(20);
|
||||
numbers.add(30);
|
||||
numbers.add(40);
|
||||
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next() == 30) {
|
||||
// will not throw Exception
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("using iterator's remove method = " + numbers);
|
||||
|
||||
iterator = numbers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next() == 40) {
|
||||
// will throw Exception on
|
||||
// next call of next() method
|
||||
numbers.remove(2);
|
||||
}
|
||||
}
|
||||
|
||||
return numbers.size();
|
||||
}
|
||||
|
||||
public static int failSafe1() {
|
||||
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
|
||||
|
||||
map.put("First", 10);
|
||||
map.put("Second", 20);
|
||||
map.put("Third", 30);
|
||||
map.put("Fourth", 40);
|
||||
|
||||
Iterator<String> iterator = map.keySet()
|
||||
.iterator();
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
String key = iterator.next();
|
||||
map.put("Fifth", 50);
|
||||
}
|
||||
|
||||
return map.size();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
class PrimitiveStreams {
|
||||
|
||||
int min(int[] integers) {
|
||||
return Arrays.stream(integers).min().getAsInt();
|
||||
}
|
||||
|
||||
int max(int... integers) {
|
||||
return IntStream.of(integers).max().getAsInt();
|
||||
}
|
||||
|
||||
int sum(int... integers) {
|
||||
return IntStream.of(integers).sum();
|
||||
}
|
||||
|
||||
double avg(int... integers) {
|
||||
return IntStream.of(integers).average().getAsDouble();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.baeldung.streamApi;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.baeldung.counter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
@@ -18,8 +19,18 @@ public class CounterStatistics {
|
||||
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
|
||||
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
|
||||
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
|
||||
private static final Map<String, Long> counterWithLongWrapperStreamMap = new HashMap<>();
|
||||
|
||||
static {
|
||||
CounterUtil.COUNTRY_NAMES = new String[10000];
|
||||
final String prefix = "NewString";
|
||||
Random random = new Random();
|
||||
for (int i=0; i<10000; i++) {
|
||||
CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@Benchmark
|
||||
public void wrapperAsCounter() {
|
||||
CounterUtil.counterWithWrapperObject(counterMap);
|
||||
}
|
||||
@@ -28,6 +39,11 @@ public class CounterStatistics {
|
||||
public void lambdaExpressionWithWrapper() {
|
||||
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void parallelStreamWithWrapper() {
|
||||
CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void mutableIntegerAsCounter() {
|
||||
|
||||
@@ -6,7 +6,7 @@ import java.util.stream.Stream;
|
||||
|
||||
public class CounterUtil {
|
||||
|
||||
private final static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
|
||||
public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
|
||||
|
||||
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
@@ -15,9 +15,14 @@ public class CounterUtil {
|
||||
}
|
||||
|
||||
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
|
||||
counterMap.putAll(Stream.of(COUNTRY_NAMES)
|
||||
Stream.of(COUNTRY_NAMES)
|
||||
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
|
||||
}
|
||||
|
||||
public static void counterWithParallelStreamAndWrapper(Map<String, Long> counterMap) {
|
||||
Stream.of(COUNTRY_NAMES)
|
||||
.parallel()
|
||||
.collect(Collectors.groupingBy(k -> k, Collectors.counting())));
|
||||
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
|
||||
}
|
||||
|
||||
public static class MutableInteger {
|
||||
@@ -38,24 +43,15 @@ public class CounterUtil {
|
||||
|
||||
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
MutableInteger oldValue = counterMap.get(country);
|
||||
if (oldValue != null) {
|
||||
oldValue.increment();
|
||||
} else {
|
||||
counterMap.put(country, new MutableInteger(1));
|
||||
}
|
||||
counterMap.compute(country, (k, v) -> v == null ? new MutableInteger(0) : v)
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
|
||||
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
int[] oldCounter = counterMap.get(country);
|
||||
if (oldCounter != null) {
|
||||
oldCounter[0] += 1;
|
||||
} else {
|
||||
counterMap.put(country, new int[] { 1 });
|
||||
}
|
||||
counterMap.compute(country, (k, v) -> v == null ? new int[] { 0 } : v)[0]++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@@ -4,7 +4,6 @@ import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.defaultistaticinterfacemethods.test;
|
||||
|
||||
import com.baeldung.defaultstaticinterfacemethods.model.Car;
|
||||
import com.baeldung.defaultstaticinterfacemethods.model.Motorbike;
|
||||
import com.baeldung.defaultstaticinterfacemethods.model.Vehicle;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class StaticDefaulInterfaceMethodUnitTest {
|
||||
|
||||
private static Car car;
|
||||
private static Motorbike motorbike;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpCarInstance() {
|
||||
car = new Car("BMW");
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpMotorbikeInstance() {
|
||||
motorbike = new Motorbike("Yamaha");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstace_whenBrandisBMW_thenOneAssertion() {
|
||||
assertThat(car.getBrand()).isEqualTo("BMW");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCallingSpeedUp_thenOneAssertion() {
|
||||
assertThat(car.speedUp()).isEqualTo("The car is speeding up.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCallingSlowDown_thenOneAssertion() {
|
||||
assertThat(car.slowDown()).isEqualTo("The car is slowing down.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCallingTurnAlarmOn_thenOneAssertion() {
|
||||
assertThat(car.turnAlarmOn()).isEqualTo("Turning the vehice alarm on.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCallingTurnAlarmOff_thenOneAssertion() {
|
||||
assertThat(car.turnAlarmOff()).isEqualTo("Turning the vehicle alarm off.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleInterface_whenCallinggetHorsePower_thenOneAssertion() {
|
||||
assertThat(Vehicle.getHorsePower(2500, 480)).isEqualTo(228);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMooorbikeInstace_whenBrandisYamaha_thenOneAssertion() {
|
||||
assertThat(motorbike.getBrand()).isEqualTo("Yamaha");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMotorbikeInstance_whenCallingSpeedUp_thenOneAssertion() {
|
||||
assertThat(motorbike.speedUp()).isEqualTo("The motorbike is speeding up.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMotorbikeInstance_whenCallingSlowDown_thenOneAssertion() {
|
||||
assertThat(motorbike.slowDown()).isEqualTo("The motorbike is slowing down.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMotorbikeInstance_whenCallingTurnAlarmOn_thenOneAssertion() {
|
||||
assertThat(motorbike.turnAlarmOn()).isEqualTo("Turning the vehice alarm on.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMotorbikeInstance_whenCallingTurnAlarmOff_thenOneAssertion() {
|
||||
assertThat(motorbike.turnAlarmOff()).isEqualTo("Turning the vehicle alarm off.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.iterators;
|
||||
|
||||
import static com.baeldung.iterators.Iterators.failFast1;
|
||||
import static com.baeldung.iterators.Iterators.failFast2;
|
||||
import static com.baeldung.iterators.Iterators.failSafe1;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Source code https://github.com/eugenp/tutorials
|
||||
*
|
||||
* @author Santosh Thakur
|
||||
*/
|
||||
|
||||
public class IteratorsTest {
|
||||
|
||||
@Test
|
||||
public void whenFailFast_ThenThrowsException() {
|
||||
assertThatThrownBy(() -> {
|
||||
failFast1();
|
||||
}).isInstanceOf(ConcurrentModificationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFailFast_ThenThrowsExceptionInSecondIteration() {
|
||||
assertThatThrownBy(() -> {
|
||||
failFast2();
|
||||
}).isInstanceOf(ConcurrentModificationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFailSafe_ThenDoesNotThrowException() {
|
||||
assertThat(failSafe1()).isGreaterThanOrEqualTo(0);
|
||||
}
|
||||
|
||||
}
|
||||
+2
-5
@@ -6,7 +6,6 @@ import java.util.Comparator;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import lombok.Data;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8ComparatorUnitTest {
|
||||
@@ -134,8 +133,7 @@ public class Java8ComparatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenThenComparing_thenSortedByAgeName() {
|
||||
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge)
|
||||
.thenComparing(Employee::getName);
|
||||
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
|
||||
|
||||
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||
@@ -144,8 +142,7 @@ public class Java8ComparatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenThenComparing_thenSortedByNameAge() {
|
||||
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName)
|
||||
.thenComparingInt(Employee::getAge);
|
||||
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
|
||||
|
||||
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PrimitiveStreamsUnitTest {
|
||||
|
||||
private PrimitiveStreams streams = new PrimitiveStreams();
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
|
||||
int[] integers = new int[] {20, 98, 12, 7, 35};
|
||||
int min = streams.min(integers); // returns 7
|
||||
|
||||
assertEquals(7, min);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenMaxIsCalledThenCorrectMaxIsReturned() {
|
||||
int max = streams.max(20, 98, 12, 7, 35);
|
||||
|
||||
assertEquals(98, max);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = streams.sum(20, 98, 12, 7, 35);
|
||||
|
||||
assertEquals(172, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenAvgIsCalledThenCorrectAvgIsReturned() {
|
||||
double avg = streams.avg(20, 98, 12, 7, 35);
|
||||
|
||||
assertTrue(34.4 == avg);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = IntStream.range(1, 10).sum();
|
||||
|
||||
assertEquals(45, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeClosedOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = IntStream.rangeClosed(1, 10).sum();
|
||||
|
||||
assertEquals(55, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeWhenForEachIsCalledThenTheIndicesWillBePrinted() {
|
||||
IntStream.rangeClosed(1, 5).parallel().forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
|
||||
|
||||
int sum = Arrays.asList(33,45).stream().mapToInt(a -> a).sum();
|
||||
|
||||
assertEquals(78, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntStreamThenGetTheEvenIntegers() {
|
||||
List<Integer> evenInts = IntStream.rangeClosed(1, 10)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
|
||||
|
||||
assertEquals(expected, evenInts);
|
||||
}
|
||||
|
||||
class Person {
|
||||
private int age;
|
||||
|
||||
Person(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
int getAge() {
|
||||
return age;
|
||||
}
|
||||
}
|
||||
}
|
||||
-1
@@ -1,7 +1,6 @@
|
||||
package com.baeldung.temporaladjusters;
|
||||
|
||||
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@@ -19,3 +19,4 @@
|
||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.baeldung.java9.varhandles;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class VariableHandlesTest {
|
||||
|
||||
public int publicTestVariable = 1;
|
||||
private int privateTestVariable = 1;
|
||||
public int variableToSet = 1;
|
||||
public int variableToCompareAndSet = 1;
|
||||
public int variableToGetAndAdd = 0;
|
||||
public byte variableToBitwiseOr = 0;
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertThat(publicIntHandle.coordinateTypes().size() == 1);
|
||||
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle privateIntHandle = MethodHandles
|
||||
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
|
||||
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
|
||||
|
||||
assertThat(privateIntHandle.coordinateTypes().size() == 1);
|
||||
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle arrayVarHandle = MethodHandles
|
||||
.arrayElementVarHandle(int[].class);
|
||||
|
||||
assertThat(arrayVarHandle.coordinateTypes().size() == 2);
|
||||
assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
|
||||
publicIntHandle.set(this, 15);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 15);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
|
||||
publicIntHandle.compareAndSet(this, 1, 100);
|
||||
|
||||
assertThat((int) publicIntHandle.get(this) == 100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
|
||||
int before = (int) publicIntHandle.getAndAdd(this, 200);
|
||||
|
||||
assertThat(before == 0);
|
||||
assertThat((int) publicIntHandle.get(this) == 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||
VarHandle publicIntHandle = MethodHandles
|
||||
.lookup()
|
||||
.in(VariableHandlesTest.class)
|
||||
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
|
||||
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
|
||||
|
||||
assertThat(before == 0);
|
||||
assertThat(variableToBitwiseOr == 127);
|
||||
}
|
||||
}
|
||||
@@ -126,3 +126,7 @@
|
||||
- [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file)
|
||||
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
|
||||
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
|
||||
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
|
||||
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
|
||||
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
||||
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
|
||||
|
||||
+445
-446
File diff suppressed because it is too large
Load Diff
@@ -25,7 +25,9 @@ public class ArrayInverter {
|
||||
}
|
||||
|
||||
public Object[] invertUsingStreams(final Object[] array) {
|
||||
return IntStream.range(1, array.length + 1).mapToObj(i -> array[array.length - i]).toArray();
|
||||
return IntStream.rangeClosed(1, array.length)
|
||||
.mapToObj(i -> array[array.length - i])
|
||||
.toArray();
|
||||
}
|
||||
|
||||
public void invertUsingCommonsLang(Object[] array) {
|
||||
|
||||
@@ -10,78 +10,60 @@ import java.util.concurrent.TimeUnit;
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
public class SearchArrayTest {
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class SearchData {
|
||||
static int count = 1000;
|
||||
static String[] strings = seedArray(1000);
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayLoop() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
searchLoop(strings, "T");
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
searchLoop(SearchData.strings, "T");
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayAllocNewList() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
searchList(strings, "W");
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
searchList(SearchData.strings, "T");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayAllocNewSet() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
searchSet(strings, "S");
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
searchSet(SearchData.strings, "T");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayReuseList() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
|
||||
List<String> asList = Arrays.asList(strings);
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
asList.contains("W");
|
||||
List<String> asList = Arrays.asList(SearchData.strings);
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
asList.contains("T");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayReuseSet() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
Set<String> asSet = new HashSet<>(Arrays.asList(strings));
|
||||
for (int i = 0; i < count; i++) {
|
||||
asSet.contains("S");
|
||||
Set<String> asSet = new HashSet<>(Arrays.asList(SearchData.strings));
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
asSet.contains("T");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
public void searchArrayBinarySearch() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
Arrays.sort(strings);
|
||||
|
||||
long startTime = System.nanoTime();
|
||||
for (int i = 0; i < count; i++) {
|
||||
Arrays.binarySearch(strings, "A");
|
||||
Arrays.sort(SearchData.strings);
|
||||
for (int i = 0; i < SearchData.count; i++) {
|
||||
Arrays.binarySearch(SearchData.strings, "T");
|
||||
}
|
||||
long duration = System.nanoTime() - startTime;
|
||||
//System.out.println("Binary search: " + duration / 10000);
|
||||
|
||||
}
|
||||
|
||||
private boolean searchList(String[] strings, String searchString) {
|
||||
@@ -101,8 +83,7 @@ public class SearchArrayTest {
|
||||
return false;
|
||||
}
|
||||
|
||||
private String[] seedArray(int length) {
|
||||
|
||||
private static String[] seedArray(int length) {
|
||||
String[] strings = new String[length];
|
||||
Random random = new Random();
|
||||
for (int i = 0; i < length; i++)
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.cipher;
|
||||
|
||||
import javax.crypto.*;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.Certificate;
|
||||
|
||||
public class Encryptor {
|
||||
|
||||
public byte[] encryptMessage(byte[] message, byte[] keyBytes) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
||||
byte[] encryptedMessage = cipher.doFinal(message);
|
||||
return encryptedMessage;
|
||||
}
|
||||
|
||||
public byte[] encryptMessage(byte[] message, Certificate publicKeyCertificate) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
|
||||
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKeyCertificate);
|
||||
byte[] encryptedMessage = cipher.doFinal(message);
|
||||
return encryptedMessage;
|
||||
}
|
||||
|
||||
public byte[] decryptMessage(byte[] encryptedMessage, byte[] keyBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey);
|
||||
byte[] clearMessage = cipher.doFinal(encryptedMessage);
|
||||
return clearMessage;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.initializationguide;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class User implements Serializable, Cloneable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
static String forum;
|
||||
private String name;
|
||||
private int id;
|
||||
|
||||
{
|
||||
id = 0;
|
||||
System.out.println("Instance Initializer");
|
||||
}
|
||||
|
||||
static {
|
||||
forum = "Java";
|
||||
System.out.println("Static Initializer");
|
||||
}
|
||||
|
||||
public User(String name, int id) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public User() {
|
||||
System.out.println("Constructor");
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.jdbc;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.UUID;
|
||||
|
||||
public class BatchProcessing {
|
||||
|
||||
private final String[] EMPLOYEES = new String[]{"Zuck","Mike","Larry","Musk","Steve"};
|
||||
private final String[] DESIGNATIONS = new String[]{"CFO","CSO","CTO","CEO","CMO"};
|
||||
private final String[] ADDRESSES = new String[]{"China","York","Diego","Carolina","India"};
|
||||
|
||||
private Connection connection;
|
||||
|
||||
public void getConnection(){
|
||||
try {
|
||||
Class.forName("org.hsqldb.jdbcDriver");
|
||||
connection = DriverManager.getConnection("jdbc:hsqldb:file:C:\\EMPLOYEEDB", "SA", "");
|
||||
connection.setAutoCommit(false);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace(System.out);
|
||||
}
|
||||
}
|
||||
|
||||
public void createTables(){
|
||||
try {
|
||||
connection.createStatement().executeUpdate("create table EMPLOYEE (ID VARCHAR(36), NAME VARCHAR(45), DESIGNATION VARCHAR(15))");
|
||||
connection.createStatement().executeUpdate("create table EMP_ADDRESS (ID VARCHAR(36), EMP_ID VARCHAR(36), ADDRESS VARCHAR(45))");
|
||||
System.out.println("Tables Created!!!");
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace(System.out);
|
||||
}
|
||||
}
|
||||
|
||||
public void useStatement(){
|
||||
try {
|
||||
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES ('%s','%s','%s');";
|
||||
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES ('%s','%s','%s');";
|
||||
Statement statement = connection.createStatement();
|
||||
for(int i = 0; i < EMPLOYEES.length; i++){
|
||||
String employeeId = UUID.randomUUID().toString();
|
||||
statement.addBatch(String.format(insertEmployeeSQL, employeeId, EMPLOYEES[i],DESIGNATIONS[i]));
|
||||
statement.addBatch(String.format(insertEmployeeAddrSQL, UUID.randomUUID().toString(),employeeId,ADDRESSES[i]));
|
||||
}
|
||||
statement.executeBatch();
|
||||
connection.commit();
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
connection.rollback();
|
||||
} catch (SQLException ex) {
|
||||
System.out.println("Error during rollback");
|
||||
System.out.println(ex.getMessage());
|
||||
}
|
||||
e.printStackTrace(System.out);
|
||||
}
|
||||
}
|
||||
|
||||
public void usePreparedStatement(){
|
||||
try {
|
||||
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);";
|
||||
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);";
|
||||
PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL);
|
||||
PreparedStatement empAddressStmt = connection.prepareStatement(insertEmployeeAddrSQL);
|
||||
for(int i = 0; i < EMPLOYEES.length; i++){
|
||||
String employeeId = UUID.randomUUID().toString();
|
||||
employeeStmt.setString(1,employeeId);
|
||||
employeeStmt.setString(2,EMPLOYEES[i]);
|
||||
employeeStmt.setString(3,DESIGNATIONS[i]);
|
||||
employeeStmt.addBatch();
|
||||
|
||||
empAddressStmt.setString(1,UUID.randomUUID().toString());
|
||||
empAddressStmt.setString(2,employeeId);
|
||||
empAddressStmt.setString(3,ADDRESSES[i]);
|
||||
empAddressStmt.addBatch();
|
||||
}
|
||||
employeeStmt.executeBatch();
|
||||
empAddressStmt.executeBatch();
|
||||
connection.commit();
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
connection.rollback();
|
||||
} catch (SQLException ex) {
|
||||
System.out.println("Error during rollback");
|
||||
System.out.println(ex.getMessage());
|
||||
}
|
||||
e.printStackTrace(System.out);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
BatchProcessing batchProcessing = new BatchProcessing();
|
||||
batchProcessing.getConnection();
|
||||
batchProcessing.createTables();
|
||||
batchProcessing.useStatement();
|
||||
batchProcessing.usePreparedStatement();
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ public class GenericFile {
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return String.format("File Name: %s\n" + " Extension: %s\n" + " Date Created: %s\n" + " Version: %s\n", this.getName(), this.getExtension(), this.getDateCreated(), this.getVersion());
|
||||
return "Generic File Impl";
|
||||
}
|
||||
|
||||
public Object read() {
|
||||
|
||||
@@ -30,7 +30,7 @@ public class ImageFile extends GenericFile {
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return String.format(" %s Height: %d\n Width: %d", super.getFileInfo(), this.getHeight(), this.getWidth());
|
||||
return "Image File Impl";
|
||||
}
|
||||
|
||||
public String read() {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user