Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 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: What’s 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: What’s 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);
}
}

Some files were not shown because too many files have changed in this diff Show More