#BAEL-16633 split Core Java 9 module - improved features

This commit is contained in:
Alessio Stalla
2019-10-29 15:30:01 +01:00
parent 83b5897387
commit fabf0993f6
24 changed files with 95 additions and 37 deletions

View File

@@ -0,0 +1,17 @@
## Core Java 9
This module contains articles about the improvements to core Java features introduced with Java 9.
### Relevant Articles:
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
#### Relevant articles not in this module:
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api) (see the [core-java-os](/core-java-os) module)

View File

@@ -0,0 +1,73 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-9</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-9</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<properties>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<guava.version>25.1-jre</guava.version>
</properties>
</project>

View File

@@ -0,0 +1,85 @@
package com.baeldung.java9;
public class Java9OptionalTest {
@Test
public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
//given
Optional<String> value = Optional.of("a");
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).hasSameElementsAs(List.of("A"));
}
@Test
public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
//given
Optional<String> value = Optional.empty();
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).isEmpty();
}
@Test
public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.of("properValue");
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(1);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
}
@Test
public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.empty();
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(0);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
}
@Test
public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
//given
String expected = "properValue";
Optional<String> value = Optional.of(expected);
Optional<String> defaultValue = Optional.of("default");
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(expected);
}
@Test
public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
//given
String defaultString = "default";
Optional<String> value = Optional.empty();
Optional<String> defaultValue = Optional.of(defaultString);
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(defaultString);
}
}

View File

@@ -0,0 +1,74 @@
package com.baeldung.java9.concurrent.future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CompletableFutureUnitTest {
@Test
public void testDelay () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.completeAsync(() -> input, CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
Thread.sleep(100);
assertFalse(future.isDone());
Thread.sleep(1000);
assertTrue(future.isDone());
assertSame(input, future.get());
}
@Test
public void testTimeoutTriggered () throws Exception {
CompletableFuture<Object> future = new CompletableFuture<>();
future.orTimeout(1, TimeUnit.SECONDS);
Thread.sleep(1100);
assertTrue(future.isDone());
try {
future.get();
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof TimeoutException);
}
}
@Test
public void testTimeoutNotTriggered () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.orTimeout(1, TimeUnit.SECONDS);
Thread.sleep(100);
future.complete(input);
Thread.sleep(1000);
assertTrue(future.isDone());
assertSame(input, future.get());
}
@Test
public void completeOnTimeout () throws Exception {
Object input = new Object();
CompletableFuture<Object> future = new CompletableFuture<>();
future.completeOnTimeout(input, 1, TimeUnit.SECONDS);
Thread.sleep(1100);
assertTrue(future.isDone());
assertSame(input, future.get());
}
}

View File

@@ -0,0 +1,86 @@
package com.baeldung.java9.language;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class Java9ObjectsAPIUnitTest {
private List<String> aMethodReturningNullList(){
return null;
}
@Test
public void givenNullObject_whenRequireNonNullElse_thenElse(){
List<String> aList = Objects.<List>requireNonNullElse(
aMethodReturningNullList(), Collections.EMPTY_LIST);
assertThat(aList, is(Collections.EMPTY_LIST));
}
private List<String> aMethodReturningNonNullList(){
return List.of("item1", "item2");
}
@Test
public void givenObject_whenRequireNonNullElse_thenObject(){
List<String> aList = Objects.<List>requireNonNullElse(
aMethodReturningNonNullList(), Collections.EMPTY_LIST);
assertThat(aList, is(List.of("item1", "item2")));
}
@Test(expected = NullPointerException.class)
public void givenNull_whenRequireNonNullElse_thenException(){
Objects.<List>requireNonNullElse(null, null);
}
@Test
public void givenObject_whenRequireNonNullElseGet_thenObject(){
List<String> aList = Objects.<List>requireNonNullElseGet(null, List::of);
assertThat(aList, is(List.of()));
}
@Test
public void givenNumber_whenInvokeCheckIndex_thenNumber(){
int length = 5;
assertThat(Objects.checkIndex(4, length), is(4));
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenOutOfRangeNumber_whenInvokeCheckIndex_thenException(){
int length = 5;
Objects.checkIndex(5, length);
}
@Test
public void givenSubRange_whenCheckFromToIndex_thenNumber(){
int length = 6;
assertThat(Objects.checkFromToIndex(2,length,length), is(2));
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenInvalidSubRange_whenCheckFromToIndex_thenException(){
int length = 6;
Objects.checkFromToIndex(2,7,length);
}
@Test
public void givenSubRange_whenCheckFromIndexSize_thenNumber(){
int length = 6;
assertThat(Objects.checkFromIndexSize(2,3,length), is(2));
}
@Test(expected = IndexOutOfBoundsException.class)
public void givenInvalidSubRange_whenCheckFromIndexSize_thenException(){
int length = 6;
Objects.checkFromIndexSize(2, 6, length);
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.java9.language.collections;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class ListFactoryMethodsUnitTest {
@Test
public void whenListCreated_thenSuccess() {
List<String> traditionlList = new ArrayList<String>();
traditionlList.add("foo");
traditionlList.add("bar");
traditionlList.add("baz");
List<String> factoryCreatedList = List.of("foo", "bar", "baz");
assertEquals(traditionlList, factoryCreatedList);
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.add("baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.set(0, "baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.remove("foo");
}
@Test(expected = NullPointerException.class)
public void onNullElem_ifNullPtrExpnThrown_thenSuccess() {
List.of("foo", "bar", null);
}
@Test
public void ifNotArrayList_thenSuccess() {
List<String> list = List.of("foo", "bar");
assertFalse(list instanceof ArrayList);
}
@Test
public void ifListSizeIsOne_thenSuccess() {
int[] arr = { 1, 2, 3, 4 };
List<int[]> list = List.of(arr);
assertEquals(1, list.size());
assertArrayEquals(arr, list.get(0));
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.java9.language.collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class MapFactoryMethodsUnitTest {
@Test
public void whenMapCreated_thenSuccess() {
Map<String, String> traditionlMap = new HashMap<String, String>();
traditionlMap.put("foo", "a");
traditionlMap.put("bar", "b");
traditionlMap.put("baz", "c");
Map<String, String> factoryCreatedMap = Map.of("foo", "a", "bar", "b", "baz", "c");
assertEquals(traditionlMap, factoryCreatedMap);
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.put("baz", "c");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.put("foo", "c");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.remove("foo");
}
@Test(expected = IllegalArgumentException.class)
public void givenDuplicateKeys_ifIllegalArgExp_thenSuccess() {
Map.of("foo", "a", "foo", "b");
}
@Test(expected = NullPointerException.class)
public void onNullKey_ifNullPtrExp_thenSuccess() {
Map.of("foo", "a", null, "b");
}
@Test(expected = NullPointerException.class)
public void onNullValue_ifNullPtrExp_thenSuccess() {
Map.of("foo", "a", "bar", null);
}
@Test
public void ifNotHashMap_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
assertFalse(map instanceof HashMap);
}
}

View File

@@ -0,0 +1,60 @@
package com.baeldung.java9.language.collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class SetFactoryMethodsUnitTest {
@Test
public void whenSetCreated_thenSuccess() {
Set<String> traditionlSet = new HashSet<String>();
traditionlSet.add("foo");
traditionlSet.add("bar");
traditionlSet.add("baz");
Set<String> factoryCreatedSet = Set.of("foo", "bar", "baz");
assertEquals(traditionlSet, factoryCreatedSet);
}
@Test(expected = IllegalArgumentException.class)
public void onDuplicateElem_IfIllegalArgExp_thenSuccess() {
Set.of("foo", "bar", "baz", "foo");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
Set<String> set = Set.of("foo", "bar");
set.add("baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
Set<String> set = Set.of("foo", "bar", "baz");
set.remove("foo");
}
@Test(expected = NullPointerException.class)
public void onNullElem_ifNullPtrExpnThrown_thenSuccess() {
Set.of("foo", "bar", null);
}
@Test
public void ifNotHashSet_thenSuccess() {
Set<String> list = Set.of("foo", "bar");
assertFalse(list instanceof HashSet);
}
@Test
public void ifSetSizeIsOne_thenSuccess() {
int[] arr = { 1, 2, 3, 4 };
Set<int[]> set = Set.of(arr);
assertEquals(1, set.size());
assertArrayEquals(arr, set.iterator().next());
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.java9.language.stream;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;
import static org.junit.Assert.assertEquals;
public class CollectorImprovementUnitTest {
@Test
public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() {
List<Integer> numbers = List.of(1, 2, 3, 5, 5);
Map<Integer, Long> result = numbers.stream().filter(val -> val > 3).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
assertEquals(1, result.size());
result = numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.filtering(val -> val > 3, Collectors.counting())));
assertEquals(4, result.size());
}
@Test
public void givenListOfBlogs_whenAuthorName_thenMapAuthorWithComments() {
Blog blog1 = new Blog("1", "Nice", "Very Nice");
Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better");
List<Blog> blogs = List.of(blog1, blog2);
Map<String, List<List<String>>> authorComments1 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.mapping(Blog::getComments, Collectors.toList())));
assertEquals(2, authorComments1.size());
assertEquals(2, authorComments1.get("1").get(0).size());
assertEquals(3, authorComments1.get("2").get(0).size());
Map<String, List<String>> authorComments2 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.flatMapping(blog -> blog.getComments().stream(), Collectors.toList())));
assertEquals(2, authorComments2.size());
assertEquals(2, authorComments2.get("1").size());
assertEquals(3, authorComments2.get("2").size());
}
}
class Blog {
private String authorName;
private List<String> comments;
public Blog(String authorName, String... comments) {
this.authorName = authorName;
this.comments = List.of(comments);
}
public String getAuthorName() {
return this.authorName;
}
public List<String> getComments() {
return this.comments;
}
}

View File

@@ -0,0 +1,111 @@
package com.baeldung.java9.language.stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.Integer.*;
import static org.junit.Assert.assertEquals;
public class StreamFeaturesUnitTest {
public static class TakeAndDropWhileTest {
public Stream<String> getStreamAfterTakeWhileOperation() {
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10);
}
public Stream<String> getStreamAfterDropWhileOperation() {
return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss"));
}
@Test
public void testTakeWhileOperation() {
List<String> list = getStreamAfterTakeWhileOperation().collect(Collectors.toList());
assertEquals(10, list.size());
assertEquals("", list.get(0));
assertEquals("ss", list.get(2));
assertEquals("sssssssss", list.get(list.size() - 1));
}
@Test
public void testDropWhileOperation() {
List<String> list = getStreamAfterDropWhileOperation().collect(Collectors.toList());
assertEquals(5, list.size());
assertEquals("sssss", list.get(0));
assertEquals("sssssss", list.get(2));
assertEquals("sssssssss", list.get(list.size() - 1));
}
}
public static class IterateTest {
private Stream<Integer> getStream() {
return Stream.iterate(0, i -> i < 10, i -> i + 1);
}
@Test
public void testIterateOperation() {
List<Integer> list = getStream().collect(Collectors.toList());
assertEquals(10, list.size());
assertEquals(valueOf(0), list.get(0));
assertEquals(valueOf(5), list.get(5));
assertEquals(valueOf(9), list.get(list.size() - 1));
}
}
public static class OfNullableTest {
private List<String> collection = Arrays.asList("A", "B", "C");
private Map<String, Integer> map = new HashMap<>() {
{
put("A", 10);
put("C", 30);
}
};
private Stream<Integer> getStreamWithOfNullable() {
return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s)));
}
private Stream<Integer> getStream() {
return collection.stream().flatMap(s -> {
Integer temp = map.get(s);
return temp != null ? Stream.of(temp) : Stream.empty();
});
}
private List<Integer> testOfNullableFrom(Stream<Integer> stream) {
List<Integer> list = stream.collect(Collectors.toList());
assertEquals(2, list.size());
assertEquals(valueOf(10), list.get(0));
assertEquals(valueOf(30), list.get(list.size() - 1));
return list;
}
@Test
public void testOfNullable() {
assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable()));
}
}
}