This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
## Guava Modules
This module contains other modules about Google Guava
+8
View File
@@ -0,0 +1,8 @@
=========
## Guava and Hamcrest Cookbooks and Examples
### Relevant Articles:
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
- [Guava 18: Whats New?](http://www.baeldung.com/whats-new-in-guava-18)
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>guava-18</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava-18</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<properties>
<guava.version>18.0</guava.version>
</properties>
</project>
@@ -0,0 +1,18 @@
package com.baeldung.guava.entity;
import com.google.common.base.MoreObjects;
public class Administrator extends User{
public Administrator(long id, String name, int age) {
super(id, name, age);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", getId())
.add("name", getName())
.add("age", getAge())
.toString();
}
}
@@ -0,0 +1,8 @@
package com.baeldung.guava.entity;
public class Player extends User{
public Player(long id, String name, int age) {
super(id, name, age);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.guava.entity;
import com.google.common.base.MoreObjects;
public class User{
private long id;
private String name;
private int age;
public User(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(User.class)
.add("id", id)
.add("name", name)
.add("age", age)
.toString();
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,80 @@
package com.baeldung.guava;
import com.baeldung.guava.entity.User;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
public class FluentIterableUnitTest {
private static final int ADULT_AGE = 18;
@Test
public void whenFilteringByAge_shouldFilterOnlyAdultUsers() throws Exception {
List<User> users = new ArrayList<>();
users.add(new User(1L, "John", 45));
users.add(new User(2L, "Michael", 27));
users.add(new User(3L, "Max", 16));
users.add(new User(4L, "Bob", 10));
users.add(new User(5L, "Bill", 65));
Predicate<User> byAge = input -> input.getAge() > ADULT_AGE;
List<String> results = FluentIterable.from(users)
.filter(byAge)
.transform(Functions.toStringFunction())
.toList();
Assert.assertThat(results.size(), equalTo(3));
}
@Test
public void whenCreatingFluentIterableFromArray_shouldContainAllUsers() throws Exception {
User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
FluentIterable<User> users = FluentIterable.of(usersArray);
Assert.assertThat(users.size(), equalTo(2));
}
@Test
public void whenAppendingElementsToFluentIterable_shouldContainAllUsers() throws Exception {
User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
FluentIterable<User> users = FluentIterable.of(usersArray).append(
new User(3L, "Bob", 23),
new User(4L, "Bill", 17)
);
Assert.assertThat(users.size(), equalTo(4));
}
@Test
public void whenAppendingListToFluentIterable_shouldContainAllUsers() throws Exception {
User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
List<User> usersList = new ArrayList<>();
usersList.add(new User(3L, "David", 32));
FluentIterable<User> users = FluentIterable.of(usersArray).append(usersList);
Assert.assertThat(users.size(), equalTo(3));
}
@Test
public void whenJoiningFluentIterableElements_shouldOutputAllUsers() throws Exception {
User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
FluentIterable<User> users = FluentIterable.of(usersArray);
Assert.assertThat(users.join(Joiner.on("; ")),
equalTo("User{id=1, name=John, age=45}; User{id=2, name=Max, age=15}"));
}
}
@@ -0,0 +1,41 @@
package com.baeldung.guava;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.net.InetAddresses;
import org.junit.Assert;
import org.junit.Test;
import java.net.InetAddress;
import java.util.concurrent.ConcurrentHashMap;
import static org.hamcrest.CoreMatchers.equalTo;
public class GuavaMiscUtilsUnitTest {
@Test
public void whenHashingData_shouldReturnCorrectHashCode() throws Exception {
int receivedData = 123;
HashCode hashCode = Hashing.crc32c().hashInt(receivedData);
Assert.assertThat(hashCode.toString(), equalTo("495be649"));
}
@Test
public void whenDecrementingIpAddress_shouldReturnOneLessIpAddress() throws Exception {
InetAddress address = InetAddress.getByName("127.0.0.5");
InetAddress decrementedAddress = InetAddresses.decrement(address);
Assert.assertThat(decrementedAddress.toString(), equalTo("/127.0.0.4"));
}
@Test
public void whenExecutingRunnableInThread_shouldLogThreadExecution() throws Exception {
ConcurrentHashMap<String, Boolean> threadExecutions = new ConcurrentHashMap<>();
Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true);
Thread t = new Thread(logThreadRun);
t.run();
Assert.assertTrue(threadExecutions.get("main"));
}
}
@@ -0,0 +1,51 @@
package com.baeldung.guava;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.*;
public class MoreExecutorsUnitTest {
@Test
public void whenExecutingRunnableInThreadPool_shouldLogAllThreadsExecutions() throws Exception {
ConcurrentHashMap<String, Boolean> threadExecutions = new ConcurrentHashMap<>();
Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true);
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(logThreadRun);
executorService.submit(logThreadRun);
executorService.shutdown();
executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
Assert.assertTrue(threadExecutions.get("pool-1-thread-1"));
Assert.assertTrue(threadExecutions.get("pool-1-thread-2"));
}
@Test
public void whenExecutingRunnableInDirectExecutor_shouldLogThreadExecution() throws Exception {
ConcurrentHashMap<String, Boolean> threadExecutions = new ConcurrentHashMap<>();
Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true);
Executor executor = MoreExecutors.directExecutor();
executor.execute(logThreadRun);
Assert.assertTrue(threadExecutions.get("main"));
}
@Test
public void whenExecutingRunnableInListeningExecutor_shouldLogThreadExecution() throws Exception {
ConcurrentHashMap<String, Boolean> threadExecutions = new ConcurrentHashMap<>();
Runnable logThreadRun = () -> threadExecutions.put(Thread.currentThread().getName(), true);
ListeningExecutorService executor = MoreExecutors.newDirectExecutorService();
executor.execute(logThreadRun);
Assert.assertTrue(threadExecutions.get("main"));
}
}
@@ -0,0 +1,33 @@
package com.baeldung.guava;
import com.baeldung.guava.entity.Administrator;
import com.baeldung.guava.entity.Player;
import com.baeldung.guava.entity.User;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
public class MoreObjectsUnitTest {
@Test
public void whenToString_shouldIncludeAllFields() throws Exception {
User user = new User(12L, "John Doe", 25);
Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}"));
}
@Test
public void whenPlayerToString_shouldCallParentToString() throws Exception {
User user = new Player(12L, "John Doe", 25);
Assert.assertThat(user.toString(), equalTo("User{id=12, name=John Doe, age=25}"));
}
@Test
public void whenAdministratorToString_shouldExecuteAdministratorToString() throws Exception {
User user = new Administrator(12L, "John Doe", 25);
Assert.assertThat(user.toString(), equalTo("Administrator{id=12, name=John Doe, age=25}"));
}
}
+7
View File
@@ -0,0 +1,7 @@
=========
## Guava 19
### Relevant Articles:
- [Guava 19: Whats New?](http://www.baeldung.com/whats-new-in-guava-19)
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>guava-19</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava-19</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<properties>
<guava.version>19.0</guava.version>
</properties>
</project>
@@ -0,0 +1,36 @@
package com.baeldung.guava.entity;
import com.google.common.base.MoreObjects;
public class User{
private long id;
private String name;
private int age;
public User(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(User.class)
.add("id", id)
.add("name", name)
.add("age", age)
.toString();
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,33 @@
package com.baeldung.guava;
import com.google.common.base.CharMatcher;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CharMatcherUnitTest {
@Test
public void whenMatchingLetterOrString_ShouldReturnTrueForCorrectString() throws Exception {
String inputString = "someString789";
boolean result = CharMatcher.javaLetterOrDigit().matchesAllOf(inputString);
assertTrue(result);
}
@Test
public void whenCollapsingString_ShouldReturnStringWithDashesInsteadOfWhitespaces() throws Exception {
String inputPhoneNumber = "8 123 456 123";
String result = CharMatcher.whitespace().collapseFrom(inputPhoneNumber, '-');
assertEquals("8-123-456-123", result);
}
@Test
public void whenCountingDigitsInString_ShouldReturnActualCountOfDigits() throws Exception {
String inputPhoneNumber = "8 123 456 123";
int result = CharMatcher.digit().countIn(inputPhoneNumber);
assertEquals(10, result);
}
}
@@ -0,0 +1,88 @@
package com.baeldung.guava;
import com.google.common.base.Throwables;
import com.google.common.collect.*;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.core.AnyOf.anyOf;
import static org.junit.Assert.*;
public class GuavaMiscUtilsUnitTest {
@Test
public void whenGettingLazyStackTrace_ListShouldBeReturned() throws Exception {
IllegalArgumentException e = new IllegalArgumentException("Some argument is incorrect");
List<StackTraceElement> stackTraceElements = Throwables.lazyStackTrace(e);
assertTrue(stackTraceElements.size() > 0);
}
@Test
public void multisetShouldCountHitsOfMultipleDuplicateObjects() throws Exception {
List<String> userNames = Arrays.asList("David", "Eugene", "Alex", "Alex", "David", "David", "David");
Multiset<String> userNamesMultiset = HashMultiset.create(userNames);
assertEquals(7, userNamesMultiset.size());
assertEquals(4, userNamesMultiset.count("David"));
assertEquals(2, userNamesMultiset.count("Alex"));
assertEquals(1, userNamesMultiset.count("Eugene"));
assertThat(userNamesMultiset.elementSet(), anyOf(containsInAnyOrder("Alex", "David", "Eugene")));
}
@Test
public void whenAddingNewConnectedRange_RangesShouldBeMerged() throws Exception {
RangeSet<Integer> rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closed(1, 10));
rangeSet.add(Range.closed(5, 15));
rangeSet.add(Range.closedOpen(10, 17));
assertTrue(rangeSet.encloses(Range.closedOpen(1, 17)));
assertTrue(rangeSet.encloses(Range.closed(2, 3)));
assertTrue(rangeSet.contains(15));
assertFalse(rangeSet.contains(17));
assertEquals(1, rangeSet.asDescendingSetOfRanges().size());
}
@Test
public void cartesianProductShouldReturnAllPossibleCombinations() throws Exception {
List<String> first = Lists.newArrayList("value1", "value2");
List<String> second = Lists.newArrayList("value3", "value4");
List<List<String>> cartesianProduct = Lists.cartesianProduct(first, second);
List<String> pair1 = Lists.newArrayList("value2", "value3");
List<String> pair2 = Lists.newArrayList("value2", "value4");
List<String> pair3 = Lists.newArrayList("value1", "value3");
List<String> pair4 = Lists.newArrayList("value1", "value4");
assertThat(cartesianProduct, anyOf(containsInAnyOrder(pair1, pair2, pair3, pair4)));
}
@Test
public void multisetShouldRemoveOccurrencesOfSpecifiedObjects() throws Exception {
Multiset<String> multisetToModify = HashMultiset.create();
Multiset<String> occurrencesToRemove = HashMultiset.create();
multisetToModify.add("John");
multisetToModify.add("Max");
multisetToModify.add("Alex");
occurrencesToRemove.add("Alex");
occurrencesToRemove.add("John");
Multisets.removeOccurrences(multisetToModify, occurrencesToRemove);
assertEquals(1, multisetToModify.size());
assertTrue(multisetToModify.contains("Max"));
assertFalse(multisetToModify.contains("John"));
assertFalse(multisetToModify.contains("Alex"));
}
}
@@ -0,0 +1,34 @@
package com.baeldung.guava;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class HashingUnitTest {
@Test
public void whenHashingInSha384_hashFunctionShouldBeReturned() throws Exception {
int inputData = 15;
HashFunction hashFunction = Hashing.sha384();
HashCode hashCode = hashFunction.hashInt(inputData);
assertEquals("0904b6277381dcfbdddd6b6c66e4e3e8f83d4690718d8e6f272c891f24773a12feaf8c449fa6e42240a621b2b5e3cda8",
hashCode.toString());
}
@Test
public void whenConcatenatingHashFunction_concatenatedHashShouldBeReturned() throws Exception {
int inputData = 15;
HashFunction hashFunction = Hashing.concatenating(Hashing.crc32(), Hashing.crc32());
HashFunction crc32Function = Hashing.crc32();
HashCode hashCode = hashFunction.hashInt(inputData);
HashCode crc32HashCode = crc32Function.hashInt(inputData);
assertEquals(crc32HashCode.toString() + crc32HashCode.toString(), hashCode.toString());
}
}
@@ -0,0 +1,45 @@
package com.baeldung.guava;
import com.google.common.reflect.TypeToken;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TypeTokenUnitTest {
@Test
public void whenCheckingIsAssignableFrom_shouldReturnTrueEvenIfGenericIsSpecified() throws Exception {
ArrayList<String> stringList = new ArrayList<>();
ArrayList<Integer> intList = new ArrayList<>();
boolean isAssignableFrom = stringList.getClass().isAssignableFrom(intList.getClass());
assertTrue(isAssignableFrom);
}
@Test
public void whenCheckingIsSupertypeOf_shouldReturnFalseIfGenericIsSpecified() throws Exception {
TypeToken<ArrayList<String>> listString = new TypeToken<ArrayList<String>>() {
};
TypeToken<ArrayList<Integer>> integerString = new TypeToken<ArrayList<Integer>>() {
};
boolean isSupertypeOf = listString.isSupertypeOf(integerString);
assertFalse(isSupertypeOf);
}
@Test
public void whenCheckingIsSubtypeOf_shouldReturnTrueIfClassIsExtendedFrom() throws Exception {
TypeToken<ArrayList<String>> stringList = new TypeToken<ArrayList<String>>() {
};
TypeToken<List> list = new TypeToken<List>() {
};
boolean isSubtypeOf = stringList.isSubtypeOf(list);
assertTrue(isSubtypeOf);
}
}
+4
View File
@@ -0,0 +1,4 @@
### Relevant articles:
- [New Stream, Comparator and Collector in Guava 21](http://www.baeldung.com/guava-21-new)
- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent)
- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip)
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>guava-21</artifactId>
<version>1.0-SNAPSHOT</version>
<name>guava-21</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
<version>${jool.version}</version>
</dependency>
</dependencies>
<properties>
<guava.version>21.0</guava.version>
<jool.version>0.9.12</jool.version>
</properties>
</project>
@@ -0,0 +1,27 @@
package com.baeldung.guava.tutorial;
import com.google.common.util.concurrent.AtomicLongMap;
public class AtomicLongMapTutorials {
private AtomicLongMap<String> atomicLongMap;
public AtomicLongMapTutorials() {
atomicLongMap = AtomicLongMap.create();
}
public void addKeys() {
atomicLongMap.addAndGet("apple", 250);
atomicLongMap.addAndGet("bat", 350);
atomicLongMap.addAndGet("cat", 450);
atomicLongMap.addAndGet("dog", 550);
}
public static void main(String[] args) {
AtomicLongMapTutorials atomicLongMapTutorials = new AtomicLongMapTutorials();
atomicLongMapTutorials.addKeys();
System.out.println(atomicLongMapTutorials.atomicLongMap.get("2"));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Comparators;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ComparatorsExamples {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 4, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(integers, new AscedingOrderComparator());
System.out.println(isInAscendingOrder);
}
private static class AscedingOrderComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}
}
@@ -0,0 +1,11 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Streams;
import java.util.stream.Stream;
public class ConcatStreams {
public static Stream concatStreams(Stream stream1, Stream stream2, Stream stream3) {
return Streams.concat(stream1, stream2, stream3);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
public class InternerBuilderExample {
public static void main(String[] args) {
Interner<Integer> interners = Interners.<Integer> newBuilder()
.concurrencyLevel(2)
.strong().<Integer> build();
}
}
@@ -0,0 +1,27 @@
package com.baeldung.guava.tutorial;
import com.google.common.util.concurrent.Monitor;
import java.util.ArrayList;
import java.util.List;
public class MonitorExample {
private List<String> students = new ArrayList<String>();
private static final int MAX_SIZE = 100;
private Monitor monitor = new Monitor();
public void addToCourse(String item) throws InterruptedException {
Monitor.Guard studentsBelowCapacity = monitor.newGuard(this::isStudentsCapacityUptoLimit);
monitor.enterWhen(studentsBelowCapacity);
try {
students.add(item);
} finally {
monitor.leave();
}
}
public Boolean isStudentsCapacityUptoLimit() {
return students.size() > MAX_SIZE;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.MoreCollectors;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class MoreCollectorsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.toOptional());
}
}
@@ -0,0 +1,39 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Streams;
import java.util.*;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class StreamsUtility {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
//Using Collection
Stream<Integer> streamFromCollection = Streams.stream(numbers);
//Using Iterator
Stream<Integer> streamFromIterator = Streams.stream(numbers.iterator());
//Using Iterable
Stream<Integer> streamFromIterable = Streams.stream((Iterable<Integer>) numbers);
//Using Optional
Stream<Integer> streamFromOptional = Streams.stream(Optional.of(1));
//Using OptionalLong to LongStream
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
//Using OptionalInt to IntStream
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
//Using OptionalDouble to DoubleStream
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
Stream<Integer> concatenatedStreams = Streams.concat(streamFromCollection, streamFromIterable, streamFromIterator);
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//This will return 10
Optional<Integer> lastItem = Streams.findLast(integers.stream());
Streams.zip(Stream.of("candy", "chocolate", "bar"), Stream.of("$1", "$2", "$3"), (arg1, arg2) -> arg1 + ":" + arg2);
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,56 @@
package com.baeldung.guava.tutorial;
import com.google.common.util.concurrent.AtomicLongMap;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AtomicLongMapIntegrationTest {
private static final String SPRING_COURSE_KEY = "Spring";
private static final String HIBERNATE_COURSE_KEY = "hibernate";
private static final String GUAVA_COURSE_KEY = "Guava";
AtomicLongMap<String> courses = AtomicLongMap.create();
public void setUp() {
courses.put(SPRING_COURSE_KEY, 1056);
courses.put(HIBERNATE_COURSE_KEY, 259);
courses.put(GUAVA_COURSE_KEY, 78);
}
@Test
public void accumulateAndGet_withLongBinaryOperator_thenSuccessful() {
long noOfStudents = 56;
long oldValue = courses.get(SPRING_COURSE_KEY);
long totalNotesRequired = courses.accumulateAndGet("Guava", noOfStudents, (x, y) -> (x * y));
assertEquals(totalNotesRequired, oldValue * noOfStudents);
}
@Test
public void getAndAccumulate_withLongBinaryOperator_thenSuccessful() {
long noOfStudents = 56;
long beforeUpdate = courses.get(SPRING_COURSE_KEY);
long onUpdate = courses.accumulateAndGet("Guava", noOfStudents, (x, y) -> (x * y));
long afterUpdate = courses.get(SPRING_COURSE_KEY);
assertEquals(onUpdate, afterUpdate);
assertEquals(afterUpdate, beforeUpdate * noOfStudents);
}
@Test
public void updateAndGet_withLongUnaryOperator_thenSuccessful() {
long beforeUpdate = courses.get(SPRING_COURSE_KEY);
long onUpdate = courses.updateAndGet("Guava", (x) -> (x / 2));
long afterUpdate = courses.get(SPRING_COURSE_KEY);
assertEquals(onUpdate, afterUpdate);
assertEquals(afterUpdate, beforeUpdate / 2);
}
}
@@ -0,0 +1,79 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Comparators;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
public class ComparatorsUnitTest {
@Test
public void isInOrderTest() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 4, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(numbers, new AscendingOrderComparator<Number>());
Assert.assertTrue(isInAscendingOrder);
}
@Test
public void isInStrictOrderTest() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 3, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(numbers, new AscendingOrderComparator<Number>());
Assert.assertFalse(isInAscendingOrder);
}
private class AscendingOrderComparator<I extends Number> implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
@Override
public Comparator<Integer> reversed() {
return null;
}
@Override
public Comparator<Integer> thenComparing(Comparator<? super Integer> other) {
return null;
}
@Override
public <U> Comparator<Integer> thenComparing(Function<? super Integer, ? extends U> keyExtractor, Comparator<? super U> keyComparator) {
return null;
}
@Override
public <U extends Comparable<? super U>> Comparator<Integer> thenComparing(Function<? super Integer, ? extends U> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingInt(ToIntFunction<? super Integer> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingLong(ToLongFunction<? super Integer> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingDouble(ToDoubleFunction<? super Integer> keyExtractor) {
return null;
}
}
}
@@ -0,0 +1,161 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Streams;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static com.baeldung.guava.tutorial.StreamUtility.assertStreamEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class GuavaStreamsUnitTest {
private List<Integer> numbers;
@Before
public void setUp() {
numbers = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());
}
@Test
public void createStreamsWithCollection() {
//Deprecated API to create stream from collection
Stream streamFromCollection = Streams.stream(numbers);
//Assert.assertNotNull(streamFromCollection);
assertStreamEquals(streamFromCollection, numbers.stream());
}
@Test
public void createStreamsWithIterable() {
Iterable<Integer> numbersIterable = numbers;
Stream streamFromIterable = Streams.stream(numbersIterable);
assertNotNull(streamFromIterable);
assertStreamEquals(streamFromIterable, numbers.stream());
}
@Test
public void createStreamsWithIterator() {
Iterator<Integer> numbersIterator = numbers.iterator();
Stream streamFromIterator = Streams.stream(numbersIterator);
assertNotNull(streamFromIterator);
assertStreamEquals(streamFromIterator, numbers.stream());
}
@Test
public void createStreamsWithOptional() {
Stream streamFromOptional = Streams.stream(Optional.of(1));
assertNotNull(streamFromOptional);
assertEquals(streamFromOptional.count(), 1);
}
@Test
public void createStreamsWithOptionalLong() {
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
assertNotNull(streamFromOptionalLong);
assertEquals(streamFromOptionalLong.count(), 1);
}
@Test
public void createStreamsWithOptionalInt() {
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
//Assert.assertNotNull(streamFromOptionalInt);
assertEquals(streamFromOptionalInt.count(), 1);
}
@Test
public void createStreamsWithOptionalDouble() {
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
//Assert.assertNotNull(streamFromOptionalDouble);
assertEquals(streamFromOptionalDouble.count(), 1);
}
@Test
public void concatStreamsOfSameType() {
List<Integer> oddNumbers = Arrays
.asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19);
List<Integer> evenNumbers = Arrays
.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20);
Stream<Integer> combinedStreams = Streams.concat(oddNumbers.stream(), evenNumbers.stream());
//Assert.assertNotNull(combinedStreams);
assertStreamEquals(combinedStreams, Stream.concat(oddNumbers.stream(), evenNumbers.stream()));
}
@Test
public void concatStreamsOfTypeLongStream() {
LongStream combinedStreams = Streams.concat(LongStream.range(1, 21), LongStream.range(21, 40));
assertNotNull(combinedStreams);
assertStreamEquals(combinedStreams, LongStream.range(1, 40));
}
@Test
public void concatStreamsOfTypeIntStream() {
IntStream combinedStreams = Streams.concat(IntStream.range(1, 20), IntStream.range(21, 40));
assertNotNull(combinedStreams);
assertStreamEquals(combinedStreams, IntStream.concat(IntStream.range(1, 20), IntStream.range(21, 40)));
}
@Test
public void findLastOfStream() {
Optional<Integer> lastElement = Streams.findLast(numbers.stream());
assertEquals(lastElement.get(), numbers.get(19));
}
@Test
public void mapWithIndexTest() {
Stream<String> stringStream = Stream.of("a", "b", "c");
Stream<String> mappedStream = Streams.mapWithIndex(stringStream, (str, index) -> str + ":" + index);
//Assert.assertNotNull(mappedStream);
assertEquals(mappedStream
.findFirst()
.get(), "a:0");
}
@Test
public void streamsZipTest() {
Stream<String> stringSream = Stream.of("a", "b", "c");
Stream<Integer> intStream = Stream.of(1, 2, 3);
Stream<String> mappedStream = Streams.zip(stringSream, intStream, (str, index) -> str + ":" + index);
//Assert.assertNotNull(mappedStream);
assertEquals(mappedStream
.findFirst()
.get(), "a:1");
}
}
@@ -0,0 +1,20 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import org.junit.Assert;
import org.junit.Test;
public class InternBuilderUnitTest {
@Test
public void interBuilderTest() {
Interner<Integer> interners = Interners.<Integer> newBuilder()
.concurrencyLevel(2)
.strong().<Integer> build();
Assert.assertNotNull(interners);
}
}
@@ -0,0 +1,55 @@
package com.baeldung.guava.tutorial;
import com.google.common.util.concurrent.Monitor;
import org.junit.Assert;
import org.junit.Test;
public class MonitorUnitTest {
@Test
public void whenGaurdConditionIsTrue_IsSuccessful() {
Monitor monitor = new Monitor();
boolean enteredInCriticalSection = false;
Monitor.Guard gaurdCondition = monitor.newGuard(this::returnTrue);
if (monitor.enterIf(gaurdCondition)) {
try {
System.out.println("Entered in critical section");
enteredInCriticalSection = true;
} finally {
monitor.leave();
}
}
Assert.assertTrue(enteredInCriticalSection);
}
@Test
public void whenGaurdConditionIsFalse_IsSuccessful() {
Monitor monitor = new Monitor();
boolean enteredInCriticalSection = false;
Monitor.Guard gaurdCondition = monitor.newGuard(this::returnFalse);
if (monitor.enterIf(gaurdCondition)) {
try {
System.out.println("Entered in critical section");
enteredInCriticalSection = true;
} finally {
monitor.leave();
}
}
Assert.assertFalse(enteredInCriticalSection);
}
private boolean returnTrue() {
return true;
}
private boolean returnFalse() {
return false;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.MoreCollectors;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class MoreCollectorsUnitTest {
@Test
public void toOptionalTest() {
List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.toOptional());
Assert.assertEquals(number.get(), new Integer(2));
}
@Test
public void onlyElementTest() {
List<Integer> numbers = Arrays.asList(1);
Integer number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.onlyElement());
Assert.assertEquals(number, new Integer(2));
}
}
@@ -0,0 +1,68 @@
package com.baeldung.guava.tutorial;
import org.junit.Assert;
import java.util.Iterator;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class StreamUtility {
public static <T> boolean assertStreamEquals(Stream<T> stream1, Stream<T> stream2) {
Iterator<T> iterator1 = stream1.iterator();
Iterator<T> iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(LongStream stream1, LongStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(DoubleStream stream1, DoubleStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(IntStream stream1, IntStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
}
@@ -0,0 +1,85 @@
package com.baeldung.guava.zip;
import com.google.common.collect.Streams;
import org.jooq.lambda.Seq;
import org.jooq.lambda.tuple.Tuple2;
import org.junit.Before;
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;
public class ZipCollectionUnitTest {
private List<String> names;
private List<Integer> ages;
private List<String> expectedOutput;
@Before
public void setUp() throws Exception {
names = Arrays.asList("John", "Jane", "Jack", "Dennis");
ages = Arrays.asList(24, 25, 27);
expectedOutput = Arrays.asList("John:24", "Jane:25", "Jack:27");
}
@Test
public void zipCollectionUsingGuava21() {
List<String> output = Streams
.zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age)
.collect(Collectors.toList());
assertEquals(output, expectedOutput);
}
@Test
public void zipCollectionUsingIntStream() {
List<String> output = IntStream
.range(0, Math.min(names.size(), ages.size()))
.mapToObj(i -> names.get(i) + ":" + ages.get(i))
.collect(Collectors.toList());
assertEquals(output, expectedOutput);
}
@Test
public void zipCollectionUsingJool() {
Seq<String> output = Seq
.of("John", "Jane", "Jack")
.zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y);
assertEquals(output.toList(), expectedOutput);
}
@Test
public void zipCollectionUsingJoolTuple() {
Seq<Tuple2<String, Integer>> output = Seq
.of("John", "Jane", "Dennis")
.zip(Seq.of(24, 25, 27));
Tuple2<String, Integer> element1 = new Tuple2<String, Integer>("John", 24);
Tuple2<String, Integer> element2 = new Tuple2<String, Integer>("Jane", 25);
Tuple2<String, Integer> element3 = new Tuple2<String, Integer>("Dennis", 27);
List<Tuple2> expectedOutput = Arrays.asList(element1, element2, element3);
assertEquals(output.collect(Collectors.toList()), expectedOutput);
}
@Test
public void zipCollectionUsingJoolWithIndex() {
Seq<Tuple2<String, Long>> output = Seq
.of("John", "Jane", "Dennis")
.zipWithIndex();
Tuple2<String, Long> element1 = new Tuple2<>("John", 0L);
Tuple2<String, Long> element2 = new Tuple2<>("Jane", 1L);
Tuple2<String, Long> element3 = new Tuple2<>("Dennis", 2L);
List<Tuple2> expectedOutput = Arrays.asList(element1, element2, element3);
assertEquals(output.collect(Collectors.toList()), expectedOutput);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>guava-modules</artifactId>
<name>guava-modules</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<modules>
<module>guava-18</module>
<module>guava-19</module>
<module>guava-21</module>
</modules>
</project>