JAVA-2154: Create guava-parent module and organize guava modules (#9782)
* JAVA-2154: Removed module, now split into guava-utilities and guava-core * JAVA-2154: Removed module, articles moved to new module guava-core * JAVA-2154: Moved module inside guava-modules * JAVA-2154: Moved module inside guava-modules * JAVA-2154: Moved module inside guava-modules * JAVA-2154: Moved module inside guava-modules * JAVA-2154: Moved 1 article to guava-collections * JAVA-2154: New module guava-collections-list * JAVA-2154: New module guava-core * JAVA-2154: New module guava-utilities * JAVA-2154: Updated README, removed extra article reference * JAVA-2154: parent module pom changes * JAVA-2154: main pom changes - removed guava related modules as they have been shifted inside guava-modules * JAVA-2154: rearranged and moved module inside guava-modules folder
This commit is contained in:
@@ -1,8 +1,5 @@
|
||||
=========
|
||||
|
||||
## Guava and Hamcrest Cookbooks and Examples
|
||||
## Guava 18
|
||||
|
||||
|
||||
### 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)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
=========
|
||||
|
||||
## Guava 19
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
## Guava 21
|
||||
|
||||
### 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)
|
||||
|
||||
@@ -13,17 +13,8 @@
|
||||
<relativePath>../</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>
|
||||
8
guava-modules/guava-collections-list/README.md
Normal file
8
guava-modules/guava-collections-list/README.md
Normal file
@@ -0,0 +1,8 @@
|
||||
## Guava Collections List examples
|
||||
|
||||
This module contains articles about list collections in Guava
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Partition a List in Java](https://www.baeldung.com/java-list-split)
|
||||
- [Guava – Lists](https://www.baeldung.com/guava-lists)
|
||||
89
guava-modules/guava-collections-list/pom.xml
Normal file
89
guava-modules/guava-collections-list/pom.xml
Normal file
@@ -0,0 +1,89 @@
|
||||
<?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-collections-list</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>guava-collections-list</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>java-hamcrest</artifactId>
|
||||
<version>${java-hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,19 @@
|
||||
<?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>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.guava.lists;
|
||||
|
||||
import com.google.common.base.Predicates;
|
||||
import com.google.common.collect.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
|
||||
public class GuavaListsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreateList_thenCreated() {
|
||||
final List<String> names = Lists.newArrayList("John", "Adam", "Jane");
|
||||
|
||||
names.add("Tom");
|
||||
assertEquals(4, names.size());
|
||||
|
||||
names.remove("Adam");
|
||||
assertThat(names, contains("John", "Jane", "Tom"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseList_thenReversed() {
|
||||
final List<String> names = Lists.newArrayList("John", "Adam", "Jane");
|
||||
|
||||
final List<String> reversed = Lists.reverse(names);
|
||||
assertThat(reversed, contains("Jane", "Adam", "John"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateCharacterListFromString_thenCreated() {
|
||||
final List<Character> chars = Lists.charactersOf("John");
|
||||
|
||||
assertEquals(4, chars.size());
|
||||
assertThat(chars, contains('J', 'o', 'h', 'n'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPartitionList_thenPartitioned() {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom", "Viki", "Tyler");
|
||||
final List<List<String>> result = Lists.partition(names, 2);
|
||||
|
||||
assertEquals(3, result.size());
|
||||
assertThat(result.get(0), contains("John", "Jane"));
|
||||
assertThat(result.get(1), contains("Adam", "Tom"));
|
||||
assertThat(result.get(2), contains("Viki", "Tyler"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveDuplicatesFromList_thenRemoved() {
|
||||
final List<Character> chars = Lists.newArrayList('h', 'e', 'l', 'l', 'o');
|
||||
assertEquals(5, chars.size());
|
||||
|
||||
final List<Character> result = ImmutableSet.copyOf(chars).asList();
|
||||
assertThat(result, contains('h', 'e', 'l', 'o'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveNullFromList_thenRemoved() {
|
||||
final List<String> names = Lists.newArrayList("John", null, "Adam", null, "Jane");
|
||||
Iterables.removeIf(names, Predicates.isNull());
|
||||
|
||||
assertEquals(3, names.size());
|
||||
assertThat(names, contains("John", "Adam", "Jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateImmutableList_thenCreated() {
|
||||
final List<String> names = Lists.newArrayList("John", "Adam", "Jane");
|
||||
|
||||
names.add("Tom");
|
||||
assertEquals(4, names.size());
|
||||
|
||||
final ImmutableList<String> immutable = ImmutableList.copyOf(names);
|
||||
assertThat(immutable, contains("John", "Adam", "Jane", "Tom"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.guava.partition;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.collections4.ListUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class CollectionApachePartitionUnitTest {
|
||||
|
||||
// tests - apache common collections
|
||||
|
||||
@Test
|
||||
public final void givenList_whenParitioningIntoNSublists_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final List<List<Integer>> subSets = ListUtils.partition(intList, 3);
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(3));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenListPartitioned_whenOriginalListIsModified_thenPartitionsChange() {
|
||||
// Given
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
final List<List<Integer>> subSets = ListUtils.partition(intList, 3);
|
||||
|
||||
// When
|
||||
intList.add(9);
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8, 9);
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.guava.partition;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class CollectionGuavaPartitionUnitTest {
|
||||
|
||||
// tests - guava
|
||||
|
||||
@Test
|
||||
public final void givenList_whenParitioningIntoNSublists_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final List<List<Integer>> subSets = Lists.partition(intList, 3);
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(3));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenListPartitioned_whenOriginalListIsModified_thenPartitionsChangeAsWell() {
|
||||
// Given
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
final List<List<Integer>> subSets = Lists.partition(intList, 3);
|
||||
|
||||
// When
|
||||
intList.add(9);
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8, 9);
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCollection_whenParitioningIntoNSublists_thenCorrect() {
|
||||
final Collection<Integer> intCollection = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final Iterable<List<Integer>> subSets = Iterables.partition(intCollection, 3);
|
||||
|
||||
// When
|
||||
final List<Integer> firstPartition = subSets.iterator().next();
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(1, 2, 3);
|
||||
assertThat(firstPartition, equalTo(expectedLastPartition));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.guava.partition;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class CollectionJavaPartitionUnitTest {
|
||||
|
||||
// java8 groupBy
|
||||
@Test
|
||||
public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final Map<Integer, List<Integer>> groups = intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
|
||||
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(3));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
|
||||
// intList.add(9);
|
||||
// System.out.println(groups.values());
|
||||
}
|
||||
|
||||
// java8 partitionBy
|
||||
@Test
|
||||
public final void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final Map<Boolean, List<Integer>> groups = intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
|
||||
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(1);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(2));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
|
||||
// intList.add(9);
|
||||
// System.out.println(groups.values());
|
||||
}
|
||||
|
||||
// java8 split by separator
|
||||
@Test
|
||||
public final void givenList_whenSplittingBySeparator_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);
|
||||
|
||||
final int[] indexes = Stream.of(IntStream.of(-1), IntStream.range(0, intList.size()).filter(i -> intList.get(i) == 0), IntStream.of(intList.size())).flatMapToInt(s -> s).toArray();
|
||||
final List<List<Integer>> subSets = IntStream.range(0, indexes.length - 1).mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])).collect(Collectors.toList());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(3));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
}
|
||||
|
||||
}
|
||||
13
guava-modules/guava-collections-map/README.md
Normal file
13
guava-modules/guava-collections-map/README.md
Normal file
@@ -0,0 +1,13 @@
|
||||
=========
|
||||
|
||||
## Guava Collections Map examples
|
||||
|
||||
This module contains articles about map collections in Guava
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guava – Maps](https://www.baeldung.com/guava-maps)
|
||||
- [Guide to Guava Multimap](https://www.baeldung.com/guava-multimap)
|
||||
- [Guide to Guava RangeMap](https://www.baeldung.com/guava-rangemap)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map)
|
||||
- [Using Guava’s MapMaker](https://www.baeldung.com/guava-mapmaker)
|
||||
54
guava-modules/guava-collections-map/pom.xml
Normal file
54
guava-modules/guava-collections-map/pom.xml
Normal file
@@ -0,0 +1,54 @@
|
||||
<?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>
|
||||
<groupId>com.baeldung.guava</groupId>
|
||||
<artifactId>guava-collections-map</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>guava-collections-map</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections-map</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.guava.mapmaker;
|
||||
|
||||
public class Profile {
|
||||
private long id;
|
||||
private String type;
|
||||
|
||||
public Profile(long id, String type) {
|
||||
this.id = id;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return type;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.guava.mapmaker;
|
||||
|
||||
public class Session {
|
||||
private long id;
|
||||
|
||||
public Session(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.guava.mapmaker;
|
||||
|
||||
public class User {
|
||||
private long id;
|
||||
private String name;
|
||||
|
||||
public User(long id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.guava.classtoinstancemap;
|
||||
import com.google.common.collect.ClassToInstanceMap;
|
||||
import com.google.common.collect.ImmutableClassToInstanceMap;
|
||||
import com.google.common.collect.MutableClassToInstanceMap;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ClassToInstanceMapUnitTest {
|
||||
@Test
|
||||
public void whenOfCalled_thenCreateEmptyImmutableMap() {
|
||||
ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.of();
|
||||
assertTrue(map.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateCalled_thenCreateEmptyMutableMap() {
|
||||
ClassToInstanceMap<Action> map = MutableClassToInstanceMap.create();
|
||||
assertTrue(map.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOfWithParameterCalled_thenCreateSingleEntryMap() {
|
||||
ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.of(Save.class, new Save());
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBuilderUser_thenCreateMap() {
|
||||
ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.<Action>builder()
|
||||
.put(Save.class, new Save())
|
||||
.put(Open.class, new Open())
|
||||
.build();
|
||||
assertEquals(2, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClassToInstanceMap_whenGetCalled_returnUpperBoundElement() {
|
||||
ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.of(Save.class, new Save());
|
||||
Action action = map.get(Save.class);
|
||||
assertTrue(action instanceof Save);
|
||||
|
||||
// Use getInstance to avoid casting
|
||||
Save save = map.getInstance(Save.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClassToInstanceMap_whenPutCalled_returnPreviousElementUpperBound() {
|
||||
ClassToInstanceMap<Action> map = MutableClassToInstanceMap.create();
|
||||
map.put(Save.class, new Save());
|
||||
// Put again to get previous value returned
|
||||
Action action = map.put(Save.class, new Save());
|
||||
assertTrue(action instanceof Save);
|
||||
|
||||
// Use putInstance to avoid casting
|
||||
Save save = map.putInstance(Save.class, new Save());
|
||||
}
|
||||
}
|
||||
|
||||
abstract class Action {
|
||||
}
|
||||
|
||||
class Save extends Action {
|
||||
}
|
||||
|
||||
class Open extends Action {
|
||||
}
|
||||
|
||||
class Delete extends Action {
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.guava.initializemaps;
|
||||
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Map;
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
public class GuavaMapInitializeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenKeyValuesShoudInitializeMap() {
|
||||
Map<String, String> articles = ImmutableMap.of("Title", "My New Article", "Title2", "Second Article");
|
||||
|
||||
assertThat(articles.get("Title"), equalTo("My New Article"));
|
||||
assertThat(articles.get("Title2"), equalTo("Second Article"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenKeyValuesShouldCreateMutableMap() {
|
||||
Map<String, String> articles = Maps.newHashMap(ImmutableMap.of("Title", "My New Article", "Title2", "Second Article"));
|
||||
|
||||
assertThat(articles.get("Title"), equalTo("My New Article"));
|
||||
assertThat(articles.get("Title2"), equalTo("Second Article"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.guava.mapmaker;
|
||||
|
||||
import com.google.common.collect.MapMaker;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class GuavaMapMakerUnitTest {
|
||||
@Test
|
||||
public void whenCreateCaches_thenCreated() {
|
||||
ConcurrentMap<User, Session> sessionCache = new MapMaker().makeMap();
|
||||
assertNotNull(sessionCache);
|
||||
|
||||
ConcurrentMap<User, Profile> profileCache = new MapMaker().makeMap();
|
||||
assertNotNull(profileCache);
|
||||
|
||||
User userA = new User(1, "UserA");
|
||||
|
||||
sessionCache.put(userA, new Session(100));
|
||||
Assert.assertThat(sessionCache.size(), equalTo(1));
|
||||
|
||||
profileCache.put(userA, new Profile(1000, "Personal"));
|
||||
Assert.assertThat(profileCache.size(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateCacheWithInitialCapacity_thenCreated() {
|
||||
ConcurrentMap<User, Profile> profileCache = new MapMaker().initialCapacity(100).makeMap();
|
||||
assertNotNull(profileCache);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateCacheWithConcurrencyLevel_thenCreated() {
|
||||
ConcurrentMap<User, Session> sessionCache = new MapMaker().concurrencyLevel(10).makeMap();
|
||||
assertNotNull(sessionCache);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateCacheWithWeakKeys_thenCreated() {
|
||||
ConcurrentMap<User, Session> sessionCache = new MapMaker().weakKeys().makeMap();
|
||||
assertNotNull(sessionCache);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateCacheWithWeakValues_thenCreated() {
|
||||
ConcurrentMap<User, Profile> profileCache = new MapMaker().weakValues().makeMap();
|
||||
assertNotNull(profileCache);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.guava.maps;
|
||||
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.collect.*;
|
||||
|
||||
public class GuavaMapsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreateImmutableMap_thenCreated() {
|
||||
final Map<String, Integer> salary = ImmutableMap.<String, Integer> builder().put("John", 1000).put("Jane", 1500).put("Adam", 2000).put("Tom", 2000).build();
|
||||
|
||||
assertEquals(1000, salary.get("John").intValue());
|
||||
assertEquals(2000, salary.get("Tom").intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseSortedMap_thenKeysAreSorted() {
|
||||
final ImmutableSortedMap<String, Integer> salary = new ImmutableSortedMap.Builder<String, Integer>(Ordering.natural()).put("John", 1000).put("Jane", 1500).put("Adam", 2000).put("Tom", 2000).build();
|
||||
|
||||
assertEquals("Adam", salary.firstKey());
|
||||
assertEquals(2000, salary.lastEntry().getValue().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateBiMap_thenCreated() {
|
||||
final BiMap<String, Integer> words = HashBiMap.create();
|
||||
words.put("First", 1);
|
||||
words.put("Second", 2);
|
||||
words.put("Third", 3);
|
||||
|
||||
assertEquals(2, words.get("Second").intValue());
|
||||
assertEquals("Third", words.inverse().get(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMultimap_thenCreated() {
|
||||
final Multimap<String, String> multimap = ArrayListMultimap.create();
|
||||
multimap.put("fruit", "apple");
|
||||
multimap.put("fruit", "banana");
|
||||
multimap.put("pet", "cat");
|
||||
multimap.put("pet", "dog");
|
||||
|
||||
assertThat(multimap.get("fruit"), containsInAnyOrder("apple", "banana"));
|
||||
assertThat(multimap.get("pet"), containsInAnyOrder("cat", "dog"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupListUsingMultimap_thenGrouped() {
|
||||
final List<String> names = Lists.newArrayList("John", "Adam", "Tom");
|
||||
final Function<String, Integer> function = new Function<String, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final String input) {
|
||||
return input.length();
|
||||
}
|
||||
};
|
||||
final Multimap<Integer, String> groups = Multimaps.index(names, function);
|
||||
|
||||
assertThat(groups.get(3), containsInAnyOrder("Tom"));
|
||||
assertThat(groups.get(4), containsInAnyOrder("John", "Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateTable_thenCreated() {
|
||||
final Table<String, String, Integer> distance = HashBasedTable.create();
|
||||
distance.put("London", "Paris", 340);
|
||||
distance.put("New York", "Los Angeles", 3940);
|
||||
distance.put("London", "New York", 5576);
|
||||
|
||||
assertEquals(3940, distance.get("New York", "Los Angeles").intValue());
|
||||
assertThat(distance.columnKeySet(), containsInAnyOrder("Paris", "New York", "Los Angeles"));
|
||||
assertThat(distance.rowKeySet(), containsInAnyOrder("London", "New York"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransposeTable_thenCorrect() {
|
||||
final Table<String, String, Integer> distance = HashBasedTable.create();
|
||||
distance.put("London", "Paris", 340);
|
||||
distance.put("New York", "Los Angeles", 3940);
|
||||
distance.put("London", "New York", 5576);
|
||||
|
||||
final Table<String, String, Integer> transposed = Tables.transpose(distance);
|
||||
assertThat(transposed.rowKeySet(), containsInAnyOrder("Paris", "New York", "Los Angeles"));
|
||||
assertThat(transposed.columnKeySet(), containsInAnyOrder("London", "New York"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateClassToInstanceMap_thenCreated() {
|
||||
final ClassToInstanceMap<Number> numbers = MutableClassToInstanceMap.create();
|
||||
numbers.putInstance(Integer.class, 1);
|
||||
numbers.putInstance(Double.class, 1.5);
|
||||
|
||||
assertEquals(1, numbers.get(Integer.class));
|
||||
assertEquals(1.5, numbers.get(Double.class));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.guava.multimap;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class GuavaMultiMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMap_whenAddTwoValuesForSameKey_shouldOverridePreviousKey() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
|
||||
//when
|
||||
map.put(key, "firstValue");
|
||||
map.put(key, "secondValue");
|
||||
|
||||
//then
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiMap_whenAddTwoValuesForSameKey_shouldHaveTwoEntriesInMap() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Multimap<String, String> map = ArrayListMultimap.create();
|
||||
|
||||
//when
|
||||
map.put(key, "firstValue");
|
||||
map.put(key, "secondValue");
|
||||
|
||||
//then
|
||||
assertEquals(2, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapOfListValues_whenAddTwoValuesForSameKey_shouldHaveTwoElementsInList() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Map<String, List<String>> map = new LinkedHashMap<>();
|
||||
|
||||
//when
|
||||
List<String> values = map.get(key);
|
||||
if(values == null){
|
||||
values = new LinkedList<>();
|
||||
values.add("firstValue");
|
||||
values.add("secondValue");
|
||||
}
|
||||
map.put(key, values);
|
||||
|
||||
//then
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.baeldung.guava.rangemap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.ImmutableRangeMap;
|
||||
import com.google.common.collect.Range;
|
||||
import com.google.common.collect.RangeMap;
|
||||
import com.google.common.collect.TreeRangeMap;
|
||||
|
||||
public class GuavaRangeMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenQueryWithinRange_returnsSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
|
||||
assertEquals("Vice President", experienceRangeDesignationMap.get(6));
|
||||
assertEquals("Executive Director", experienceRangeDesignationMap.get(15));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenQueryOutsideRange_returnsNull() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
|
||||
assertNull(experienceRangeDesignationMap.get(31));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenRemoveRangeIsCalled_removesSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
experienceRangeDesignationMap.remove(Range.closed(8, 15));
|
||||
experienceRangeDesignationMap.remove(Range.closed(20, 26));
|
||||
|
||||
assertNull(experienceRangeDesignationMap.get(9));
|
||||
assertEquals("Managing Director", experienceRangeDesignationMap.get(16));
|
||||
assertEquals("Managing Director", experienceRangeDesignationMap.get(30));
|
||||
assertNull(experienceRangeDesignationMap.get(25));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenSpanIsCalled_returnsSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
final Range<Integer> experienceSpan = experienceRangeDesignationMap.span();
|
||||
|
||||
assertEquals(0, experienceSpan.lowerEndpoint().intValue());
|
||||
assertEquals(30, experienceSpan.upperEndpoint().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenGetEntryIsCalled_returnsEntrySucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(20, 30), "Managing Director");
|
||||
final Map.Entry<Range<Integer>, String> experiencEntry = experienceRangeDesignationMap.getEntry(10);
|
||||
|
||||
assertEquals(Range.closed(9, 15), experiencEntry.getKey());
|
||||
assertEquals("Executive Director", experiencEntry.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenSubRangeMapIsCalled_returnsSubRangeSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(8, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
final RangeMap<Integer, String> experiencedSubRangeDesignationMap = experienceRangeDesignationMap.subRangeMap(Range.closed(4, 14));
|
||||
|
||||
assertNull(experiencedSubRangeDesignationMap.get(3));
|
||||
assertTrue(experiencedSubRangeDesignationMap.asMapOfRanges().values()
|
||||
.containsAll(Arrays.asList("Executive Director", "Vice President", "Executive Director")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableRangeMap_whenQueryWithinRange_returnsSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = ImmutableRangeMap.<Integer, String> builder()
|
||||
.put(Range.closed(0, 2), "Associate")
|
||||
.put(Range.closed(3, 5), "Senior Associate")
|
||||
.put(Range.closed(6, 8), "Vice President")
|
||||
.put(Range.closed(9, 15), "Executive Director")
|
||||
.put(Range.closed(16, 30), "Managing Director").build();
|
||||
|
||||
assertEquals("Vice President", experienceRangeDesignationMap.get(6));
|
||||
assertEquals("Executive Director", experienceRangeDesignationMap.get(15));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenImmutableRangeMap_whenRangeOverlaps_ThrowsException() {
|
||||
ImmutableRangeMap.<Integer, String> builder()
|
||||
.put(Range.closed(0, 2), "Associate")
|
||||
.put(Range.closed(3, 5), "Senior Associate")
|
||||
.put(Range.closed(6, 8), "Vice President")
|
||||
.put(Range.closed(8, 15), "Executive Director")
|
||||
.put(Range.closed(16, 30), "Managing Director").build();
|
||||
|
||||
}
|
||||
}
|
||||
13
guava-modules/guava-collections-set/.gitignore
vendored
Normal file
13
guava-modules/guava-collections-set/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
10
guava-modules/guava-collections-set/README.md
Normal file
10
guava-modules/guava-collections-set/README.md
Normal file
@@ -0,0 +1,10 @@
|
||||
## Guava Collections Set
|
||||
|
||||
This module contains articles about Google Guava sets
|
||||
|
||||
## Relevant Articles:
|
||||
|
||||
- [Guava – Sets](https://www.baeldung.com/guava-sets)
|
||||
- [Guide to Guava RangeSet](https://www.baeldung.com/guava-rangeset)
|
||||
- [Guava Set + Function = Map](https://www.baeldung.com/guava-set-function-map-tutorial)
|
||||
- [Guide to Guava Multiset](https://www.baeldung.com/guava-multiset)
|
||||
56
guava-modules/guava-collections-set/pom.xml
Normal file
56
guava-modules/guava-collections-set/pom.xml
Normal file
@@ -0,0 +1,56 @@
|
||||
<?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-collections-set</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>guava-collections-set</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections-set</finalName>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
|
||||
|
||||
private class SingleEntry implements Entry<K, V> {
|
||||
private K key;
|
||||
|
||||
public SingleEntry(K key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public K getKey() {
|
||||
return this.key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public V getValue() {
|
||||
V value = GuavaMapFromSet.this.cache.get(this.key);
|
||||
if (value == null) {
|
||||
value = GuavaMapFromSet.this.function.apply(this.key);
|
||||
GuavaMapFromSet.this.cache.put(this.key, value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public V setValue(V value) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
private class MyEntrySet extends AbstractSet<Entry<K, V>> {
|
||||
|
||||
public class EntryIterator implements Iterator<Entry<K, V>> {
|
||||
private Iterator<K> inner;
|
||||
|
||||
public EntryIterator() {
|
||||
this.inner = MyEntrySet.this.keys.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return this.inner.hasNext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map.Entry<K, V> next() {
|
||||
K key = this.inner.next();
|
||||
return new SingleEntry(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
private Set<K> keys;
|
||||
|
||||
public MyEntrySet(Set<K> keys) {
|
||||
this.keys = keys;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<Map.Entry<K, V>> iterator() {
|
||||
return new EntryIterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return this.keys.size();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private WeakHashMap<K, V> cache;
|
||||
private Set<Entry<K, V>> entries;
|
||||
private Function<? super K, ? extends V> function;
|
||||
|
||||
public GuavaMapFromSet(Set<K> keys, Function<? super K, ? extends V> function) {
|
||||
this.function = function;
|
||||
this.cache = new WeakHashMap<K, V>();
|
||||
this.entries = new MyEntrySet(keys);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Map.Entry<K, V>> entrySet() {
|
||||
return this.entries;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class GuavaMapFromSetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStringSet_whenMapsToElementLength_thenCorrect() {
|
||||
Function<Integer, String> function = new Function<Integer, String>() {
|
||||
@Override
|
||||
public String apply(Integer from) {
|
||||
return Integer.toBinaryString(from);
|
||||
}
|
||||
};
|
||||
Set<Integer> set = new TreeSet<>(Arrays.asList(32, 64, 128));
|
||||
Map<Integer, String> map = new GuavaMapFromSet<Integer, String>(set, function);
|
||||
assertTrue(map.get(32).equals("100000")
|
||||
&& map.get(64).equals("1000000")
|
||||
&& map.get(128).equals("10000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntSet_whenMapsToElementBinaryValue_thenCorrect() {
|
||||
Function<String, Integer> function = new Function<String, Integer>() {
|
||||
|
||||
@Override
|
||||
public Integer apply(String from) {
|
||||
return from.length();
|
||||
}
|
||||
};
|
||||
Set<String> set = new TreeSet<>(Arrays.asList(
|
||||
"four", "three", "twelve"));
|
||||
Map<String, Integer> map = new GuavaMapFromSet<String, Integer>(set,
|
||||
function);
|
||||
assertTrue(map.get("four") == 4 && map.get("three") == 5
|
||||
&& map.get("twelve") == 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_whenNewSetElementAddedAndMappedLive_thenCorrect() {
|
||||
Function<String, Integer> function = new Function<String, Integer>() {
|
||||
|
||||
@Override
|
||||
public Integer apply(String from) {
|
||||
return from.length();
|
||||
}
|
||||
};
|
||||
Set<String> set = new TreeSet<>(Arrays.asList(
|
||||
"four", "three", "twelve"));
|
||||
Map<String, Integer> map = new GuavaMapFromSet<String, Integer>(set,
|
||||
function);
|
||||
set.add("one");
|
||||
assertTrue(map.get("one") == 3 && map.size() == 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.collect.HashMultiset;
|
||||
import com.google.common.collect.Multiset;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class GuavaMultiSetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenAddingValues_shouldReturnCorrectCount() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
|
||||
assertThat(bookStore.contains("Potter")).isTrue();
|
||||
assertThat(bookStore.count("Potter")).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenRemovingValues_shouldReturnCorrectCount() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
|
||||
bookStore.remove("Potter");
|
||||
assertThat(bookStore.contains("Potter")).isTrue();
|
||||
assertThat(bookStore.count("Potter")).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSetCount_shouldReturnCorrectCount() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.setCount("Potter", 50);
|
||||
assertThat(bookStore.count("Potter")).isEqualTo(50);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSettingNegativeCount_shouldThrowException() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
assertThatThrownBy(() -> bookStore.setCount("Potter", -1))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSettingCountWithEmptySet_shouldBeSuccessful() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
assertThat(bookStore.setCount("Potter", 0, 2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSettingCountWithCorrectValue_shouldBeSuccessful() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
|
||||
assertThat(bookStore.setCount("Potter", 2, 52)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiSet_whenSettingCountWithIncorrectValue_shouldFail() {
|
||||
Multiset<String> bookStore = HashMultiset.create();
|
||||
bookStore.add("Potter");
|
||||
bookStore.add("Potter");
|
||||
|
||||
assertThat(bookStore.setCount("Potter", 5, 52)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_compareMultiSetOperations() {
|
||||
Map<String, Integer> bookStore = new HashMap<>();
|
||||
bookStore.put("Potter", 3);
|
||||
|
||||
assertThat(bookStore.containsKey("Potter")).isTrue();
|
||||
assertThat(bookStore.get("Potter")).isEqualTo(3);
|
||||
|
||||
bookStore.put("Potter", 2);
|
||||
assertThat(bookStore.get("Potter")).isEqualTo(2);
|
||||
|
||||
bookStore.put("Potter", null);
|
||||
assertThat(bookStore.containsKey("Potter")).isTrue();
|
||||
|
||||
bookStore.put("Potter", -1);
|
||||
assertThat(bookStore.containsKey("Potter")).isTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.collect.ImmutableRangeSet;
|
||||
import com.google.common.collect.Range;
|
||||
import com.google.common.collect.RangeSet;
|
||||
import com.google.common.collect.TreeRangeSet;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class GuavaRangeSetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenQueryWithinRange_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
|
||||
assertTrue(numberRangeSet.contains(1));
|
||||
assertFalse(numberRangeSet.contains(9));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenEnclosesWithinRange_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 10));
|
||||
numberRangeSet.add(Range.closed(15, 18));
|
||||
|
||||
assertTrue(numberRangeSet.encloses(Range.closed(4, 5)));
|
||||
assertFalse(numberRangeSet.encloses(Range.closed(4, 11)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenComplementIsCalled_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
final RangeSet<Integer> numberRangeComplementSet = numberRangeSet.complement();
|
||||
|
||||
assertTrue(numberRangeComplementSet.contains(-1000));
|
||||
assertFalse(numberRangeComplementSet.contains(2));
|
||||
assertFalse(numberRangeComplementSet.contains(3));
|
||||
assertTrue(numberRangeComplementSet.contains(1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenIntersectsWithinRange_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 10));
|
||||
numberRangeSet.add(Range.closed(15, 18));
|
||||
|
||||
assertTrue(numberRangeSet.intersects(Range.closed(4, 17)));
|
||||
assertFalse(numberRangeSet.intersects(Range.closed(19, 200)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenRemoveRangeIsCalled_removesSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
numberRangeSet.add(Range.closed(9, 15));
|
||||
numberRangeSet.remove(Range.closed(3, 5));
|
||||
numberRangeSet.remove(Range.closed(7, 10));
|
||||
|
||||
assertTrue(numberRangeSet.contains(1));
|
||||
assertFalse(numberRangeSet.contains(9));
|
||||
assertTrue(numberRangeSet.contains(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenSpanIsCalled_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
final Range<Integer> experienceSpan = numberRangeSet.span();
|
||||
|
||||
assertEquals(0, experienceSpan.lowerEndpoint().intValue());
|
||||
assertEquals(8, experienceSpan.upperEndpoint().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenSubRangeSetIsCalled_returnsSubRangeSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
final RangeSet<Integer> numberSubRangeSet = numberRangeSet.subRangeSet(Range.closed(4, 14));
|
||||
|
||||
assertFalse(numberSubRangeSet.contains(3));
|
||||
assertFalse(numberSubRangeSet.contains(14));
|
||||
assertTrue(numberSubRangeSet.contains(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableRangeSet_whenQueryWithinRange_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = ImmutableRangeSet.<Integer> builder()
|
||||
.add(Range.closed(0, 2))
|
||||
.add(Range.closed(3, 5))
|
||||
.add(Range.closed(6, 8)).build();
|
||||
|
||||
assertTrue(numberRangeSet.contains(6));
|
||||
assertFalse(numberRangeSet.contains(15));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenImmutableRangeMap_whenRangeOverlaps_ThrowsException() {
|
||||
ImmutableRangeSet.<Integer> builder()
|
||||
.add(Range.closed(0, 2))
|
||||
.add(Range.closed(3, 5))
|
||||
.add(Range.closed(5, 8)).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.baeldung.guava;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.collect.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class GuavaSetOperationsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalculatingUnionOfSets_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> union = Sets.union(first, second);
|
||||
assertThat(union, containsInAnyOrder('a', 'b', 'c', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingCartesianProductOfSets_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b');
|
||||
final Set<Character> second = ImmutableSet.of('c', 'd');
|
||||
final Set<List<Character>> result = Sets.cartesianProduct(ImmutableList.of(first, second));
|
||||
|
||||
final Function<List<Character>, String> func = new Function<List<Character>, String>() {
|
||||
@Override
|
||||
public final String apply(final List<Character> input) {
|
||||
return Joiner
|
||||
.on(" ").join(input);
|
||||
}
|
||||
};
|
||||
|
||||
final Iterable<String> joined = Iterables.transform(result, func);
|
||||
assertThat(joined, containsInAnyOrder("a c", "a d", "b c", "b d"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetIntersection_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.intersection(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('b', 'c'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetSymmetricDifference_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.symmetricDifference(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('a', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingPowerSet_thenCorrect() {
|
||||
final Set<Character> chars = ImmutableSet.of('a', 'b');
|
||||
final Set<Set<Character>> result = Sets.powerSet(chars);
|
||||
|
||||
final Set<Character> empty = ImmutableSet.<Character> builder().build();
|
||||
final Set<Character> a = ImmutableSet.of('a');
|
||||
final Set<Character> b = ImmutableSet.of('b');
|
||||
final Set<Character> aB = ImmutableSet.of('a', 'b');
|
||||
|
||||
assertThat(result, contains(empty, a, b, aB));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingRangeOfIntegersSet_thenCreated() {
|
||||
final int start = 10;
|
||||
final int end = 30;
|
||||
final ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(start, end), DiscreteDomain.integers());
|
||||
|
||||
assertEquals(21, set.size());
|
||||
assertEquals(10, set.first().intValue());
|
||||
assertEquals(30, set.last().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRangeSet_thenCorrect() {
|
||||
final RangeSet<Integer> rangeSet = TreeRangeSet.create();
|
||||
rangeSet.add(Range.closed(1, 10));
|
||||
rangeSet.add(Range.closed(12, 15));
|
||||
|
||||
assertEquals(2, rangeSet.asRanges().size());
|
||||
|
||||
rangeSet.add(Range.closed(10, 12));
|
||||
assertTrue(rangeSet.encloses(Range.closed(1, 15)));
|
||||
assertEquals(1, rangeSet.asRanges().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertDuplicatesInMultiSet_thenInserted() {
|
||||
final Multiset<String> names = HashMultiset.create();
|
||||
names.add("John");
|
||||
names.add("Adam", 3);
|
||||
names.add("John");
|
||||
|
||||
assertEquals(2, names.count("John"));
|
||||
names.remove("John");
|
||||
assertEquals(1, names.count("John"));
|
||||
|
||||
assertEquals(3, names.count("Adam"));
|
||||
names.remove("Adam", 2);
|
||||
assertEquals(1, names.count("Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetTopOcurringElementsWithMultiSet_thenCorrect() {
|
||||
final Multiset<String> names = HashMultiset.create();
|
||||
names.add("John");
|
||||
names.add("Adam", 5);
|
||||
names.add("Jane");
|
||||
names.add("Tom", 2);
|
||||
|
||||
final Set<String> sorted = Multisets.copyHighestCountFirst(names).elementSet();
|
||||
final List<String> topTwo = Lists.newArrayList(sorted).subList(0, 2);
|
||||
assertEquals(2, topTwo.size());
|
||||
assertEquals("Adam", topTwo.get(0));
|
||||
assertEquals("Tom", topTwo.get(1));
|
||||
}
|
||||
}
|
||||
15
guava-modules/guava-collections/README.md
Normal file
15
guava-modules/guava-collections/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## Guava Collections
|
||||
|
||||
This module contains articles about Google Guava collections
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Guava Collections Cookbook](https://www.baeldung.com/guava-collections)
|
||||
- [Guava Ordering Cookbook](https://www.baeldung.com/guava-order)
|
||||
- [Guide to Guava’s Ordering](https://www.baeldung.com/guava-ordering)
|
||||
- [Hamcrest Collections Cookbook](https://www.baeldung.com/hamcrest-collections-arrays)
|
||||
- [Filtering and Transforming Collections in Guava](https://www.baeldung.com/guava-filter-and-transform-a-collection)
|
||||
- [Guava – Join and Split Collections](https://www.baeldung.com/guava-joiner-and-splitter-tutorial)
|
||||
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](https://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
|
||||
- [Guide to Guava Table](https://www.baeldung.com/guava-table)
|
||||
- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip)
|
||||
95
guava-modules/guava-collections/pom.xml
Normal file
95
guava-modules/guava-collections/pom.xml
Normal file
@@ -0,0 +1,95 @@
|
||||
<?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-collections</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>guava-collections</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jool</artifactId>
|
||||
<version>${jool.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>java-hamcrest</artifactId>
|
||||
<version>${java-hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava-collections</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<jool.version>0.9.12</jool.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,19 @@
|
||||
<?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>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.baeldung.guava.collections;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Predicates;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class GuavaCollectionsExamplesUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenDowncastingGenerifiedCollectionToNewGenerifiedCollection_thenCastIsOK() {
|
||||
final class CastFunction<F, T extends F> implements Function<F, T> {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public final T apply(final F from) {
|
||||
return (T) from;
|
||||
}
|
||||
}
|
||||
|
||||
final List<Number> originalList = Lists.newArrayList();
|
||||
final List<Integer> selectedProducts = Lists.transform(originalList, new CastFunction<Number, Integer>());
|
||||
System.out.println(selectedProducts);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
@Test
|
||||
public final void whenDowncastingGenerifiedCollectionToNewGenerifiedCollection_thenCastIsOK2() {
|
||||
final List<Number> originalList = Lists.newArrayList();
|
||||
final List<Integer> selectedProducts = (List<Integer>) (List<? extends Number>) originalList;
|
||||
System.out.println(selectedProducts);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenAddingAnIterableToACollection_thenAddedOK() {
|
||||
final Iterable<String> iter = Lists.newArrayList();
|
||||
final Collection<String> collector = Lists.newArrayList();
|
||||
Iterables.addAll(collector, iter);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public final void whenCheckingIfCollectionContainsElementsByCustomMatch1_thenContains() {
|
||||
final Iterable<String> theCollection = Lists.newArrayList("a", "bc", "def");
|
||||
final boolean contains = Iterables.any(theCollection, new Predicate<String>() {
|
||||
@Override
|
||||
public final boolean apply(final String input) {
|
||||
return input.length() == 1;
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue(contains);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCheckingIfCollectionContainsElementsByCustomMatch2_thenContains() {
|
||||
final Set<String> theCollection = Sets.newHashSet("a", "bc", "def");
|
||||
|
||||
final boolean contains = !Sets.filter(theCollection, new Predicate<String>() {
|
||||
@Override
|
||||
public final boolean apply(final String input) {
|
||||
return input.length() == 1;
|
||||
}
|
||||
}).isEmpty();
|
||||
|
||||
assertTrue(contains);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCheckingIfCollectionContainsElementsByCustomMatch3_thenContains() {
|
||||
final Iterable<String> theCollection = Sets.newHashSet("a", "bc", "def");
|
||||
|
||||
final boolean contains = Iterables.find(theCollection, new Predicate<String>() {
|
||||
@Override
|
||||
public final boolean apply(final String input) {
|
||||
return input.length() == 1;
|
||||
}
|
||||
}) != null;
|
||||
|
||||
assertTrue(contains);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test(expected = NoSuchElementException.class)
|
||||
public final void givenNoSearchResult_whenFindingElementInIterable_thenException() {
|
||||
final Iterable<String> theCollection = Sets.newHashSet("abcd", "efgh", "ijkl");
|
||||
|
||||
final String found = Iterables.find(theCollection, new Predicate<String>() {
|
||||
@Override
|
||||
public final boolean apply(final String input) {
|
||||
return input.length() == 1;
|
||||
}
|
||||
});
|
||||
|
||||
assertNull(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNoSearchResult_whenFindingElementInIterableWithSpecifiedReturn_thenNoException() {
|
||||
final Iterable<String> theCollection = Sets.newHashSet("abcd", "efgh", "ijkl");
|
||||
|
||||
final Predicate<String> inputOfLengthOne = new Predicate<String>() {
|
||||
@Override
|
||||
public final boolean apply(final String input) {
|
||||
return input.length() == 1;
|
||||
}
|
||||
};
|
||||
final String found = Iterables.find(theCollection, inputOfLengthOne, null);
|
||||
|
||||
assertNull(found);
|
||||
}
|
||||
|
||||
// purge of nulls
|
||||
|
||||
@Test
|
||||
public final void givenListContainsNulls_whenPurgedOfNulls_thenNoLongerContainsNulls() {
|
||||
final List<String> values = Lists.newArrayList("a", null, "b", "c");
|
||||
final Iterable<String> withoutNulls = Iterables.filter(values, Predicates.notNull());
|
||||
System.out.println(withoutNulls);
|
||||
}
|
||||
|
||||
// immutable collections
|
||||
|
||||
@Test
|
||||
public final void whenCreatingImuutableCollections_thenNoExceptions() {
|
||||
final ImmutableList<String> immutableList = ImmutableList.of("a", "b", "c");
|
||||
final ImmutableSet<String> immutableSet = ImmutableSet.of("a", "b", "c");
|
||||
final ImmutableMap<String, String> imuttableMap = ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenTransformingCollectionsToImmutable_thenNoExceptions() {
|
||||
final List<String> muttableList = Lists.newArrayList();
|
||||
final ImmutableList<String> immutableList = ImmutableList.copyOf(muttableList);
|
||||
|
||||
final Set<String> muttableSet = Sets.newHashSet();
|
||||
final ImmutableSet<String> immutableSet = ImmutableSet.copyOf(muttableSet);
|
||||
|
||||
final Map<String, String> muttableMap = Maps.newHashMap();
|
||||
final ImmutableMap<String, String> imuttableMap = ImmutableMap.copyOf(muttableMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenTransformingCollectionsToImmutableViaBuilders_thenNoExceptions() {
|
||||
final List<String> muttableList = Lists.newArrayList();
|
||||
final ImmutableList<String> immutableList = ImmutableList.<String> builder().addAll(muttableList).build();
|
||||
|
||||
final Set<String> muttableSet = Sets.newHashSet();
|
||||
final ImmutableSet<String> immutableSet = ImmutableSet.<String> builder().addAll(muttableSet).build();
|
||||
|
||||
final Map<String, String> muttableMap = Maps.newHashMap();
|
||||
final ImmutableMap<String, String> imuttableMap = ImmutableMap.<String, String> builder().putAll(muttableMap).build();
|
||||
}
|
||||
|
||||
// unmodifiable
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public final void givenUnmodifiableViewOverIterable_whenTryingToRemove_thenNotAllowed() {
|
||||
final List<Integer> numbers = Lists.newArrayList(1, 2, 3);
|
||||
final Iterable<Integer> unmodifiableIterable = Iterables.unmodifiableIterable(numbers);
|
||||
final Iterator<Integer> iterator = unmodifiableIterable.iterator();
|
||||
if (iterator.hasNext()) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package com.baeldung.guava.filtertransform;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Functions;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Predicates;
|
||||
import com.google.common.collect.Collections2;
|
||||
import com.google.common.collect.FluentIterable;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class GuavaFilterTransformCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFilterWithIterables_thenFiltered() {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Iterable<String> result = Iterables.filter(names, Predicates.containsPattern("a"));
|
||||
|
||||
assertThat(result, containsInAnyOrder("Jane", "Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterWithCollections2_thenFiltered() {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Collection<String> result = Collections2.filter(names, Predicates.containsPattern("a"));
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertThat(result, containsInAnyOrder("Jane", "Adam"));
|
||||
|
||||
result.add("anna");
|
||||
assertEquals(5, names.size());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenFilteredCollection_whenAddingInvalidElement_thenException() {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Collection<String> result = Collections2.filter(names, Predicates.containsPattern("a"));
|
||||
|
||||
result.add("elvis");
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenFilterCollectionWithCustomPredicate_thenFiltered() {
|
||||
final Predicate<String> predicate = new Predicate<String>() {
|
||||
@Override
|
||||
public final boolean apply(final String input) {
|
||||
return input.startsWith("A") || input.startsWith("J");
|
||||
}
|
||||
};
|
||||
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Collection<String> result = Collections2.filter(names, predicate);
|
||||
|
||||
assertEquals(3, result.size());
|
||||
assertThat(result, containsInAnyOrder("John", "Jane", "Adam"));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenRemoveNullFromCollection_thenRemoved() {
|
||||
final List<String> names = Lists.newArrayList("John", null, "Jane", null, "Adam", "Tom");
|
||||
final Collection<String> result = Collections2.filter(names, Predicates.notNull());
|
||||
|
||||
assertEquals(4, result.size());
|
||||
assertThat(result, containsInAnyOrder("John", "Jane", "Adam", "Tom"));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenCheckingIfAllElementsMatchACondition_thenCorrect() {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
|
||||
boolean result = Iterables.all(names, Predicates.containsPattern("n|m"));
|
||||
assertTrue(result);
|
||||
|
||||
result = Iterables.all(names, Predicates.containsPattern("a"));
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenTransformingWithIterables_thenTransformed() {
|
||||
final Function<String, Integer> function = new Function<String, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final String input) {
|
||||
return input.length();
|
||||
}
|
||||
};
|
||||
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Iterable<Integer> result = Iterables.transform(names, function);
|
||||
|
||||
assertThat(result, contains(4, 4, 4, 3));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenTransformWithCollections2_thenTransformed() {
|
||||
final Function<String, Integer> function = new Function<String, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final String input) {
|
||||
return input.length();
|
||||
}
|
||||
};
|
||||
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Collection<Integer> result = Collections2.transform(names, function);
|
||||
|
||||
assertEquals(4, result.size());
|
||||
assertThat(result, contains(4, 4, 4, 3));
|
||||
|
||||
result.remove(3);
|
||||
assertEquals(3, names.size());
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenCreatingAFunctionFromAPredicate_thenCorrect() {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Collection<Boolean> result = Collections2.transform(names, Functions.forPredicate(Predicates.containsPattern("m")));
|
||||
|
||||
assertEquals(4, result.size());
|
||||
assertThat(result, contains(false, false, true, true));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenTransformingUsingComposedFunction_thenTransformed() {
|
||||
final Function<String, Integer> f1 = new Function<String, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final String input) {
|
||||
return input.length();
|
||||
}
|
||||
};
|
||||
|
||||
final Function<Integer, Boolean> f2 = new Function<Integer, Boolean>() {
|
||||
@Override
|
||||
public final Boolean apply(final Integer input) {
|
||||
return input % 2 == 0;
|
||||
}
|
||||
};
|
||||
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Collection<Boolean> result = Collections2.transform(names, Functions.compose(f2, f1));
|
||||
|
||||
assertEquals(4, result.size());
|
||||
assertThat(result, contains(true, true, true, false));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenFilteringAndTransformingCollection_thenCorrect() {
|
||||
final Predicate<String> predicate = new Predicate<String>() {
|
||||
@Override
|
||||
public final boolean apply(final String input) {
|
||||
return input.startsWith("A") || input.startsWith("T");
|
||||
}
|
||||
};
|
||||
|
||||
final Function<String, Integer> func = new Function<String, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final String input) {
|
||||
return input.length();
|
||||
}
|
||||
};
|
||||
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Collection<Integer> result = FluentIterable.from(names).filter(predicate).transform(func).toList();
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertThat(result, containsInAnyOrder(4, 3));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenFilterUsingMultiplePredicates_thenFiltered() {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final Collection<String> result = Collections2.filter(names, Predicates.or(Predicates.containsPattern("J"), Predicates.not(Predicates.containsPattern("a"))));
|
||||
|
||||
assertEquals(3, result.size());
|
||||
assertThat(result, containsInAnyOrder("John", "Jane", "Tom"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.baeldung.guava.joinsplit;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
public class GuavaStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenConvertListToString_thenConverted() {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final String result = Joiner.on(",").join(names);
|
||||
|
||||
assertEquals(result, "John,Jane,Adam,Tom");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertListToStringAndSkipNull_thenConverted() {
|
||||
final List<String> names = Lists.newArrayList("John", null, "Jane", "Adam", "Tom");
|
||||
final String result = Joiner.on(",").skipNulls().join(names);
|
||||
|
||||
assertEquals(result, "John,Jane,Adam,Tom");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertMapToString_thenConverted() {
|
||||
final Map<String, Integer> salary = Maps.newHashMap();
|
||||
salary.put("John", 1000);
|
||||
salary.put("Jane", 1500);
|
||||
|
||||
final String result = Joiner.on(" , ").withKeyValueSeparator(" = ").join(salary);
|
||||
|
||||
assertThat(result, containsString("John = 1000"));
|
||||
assertThat(result, containsString("Jane = 1500"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoinNestedCollections_thenJoined() {
|
||||
final List<ArrayList<String>> nested = Lists.newArrayList(Lists.newArrayList("apple", "banana", "orange"), Lists.newArrayList("cat", "dog", "bird"), Lists.newArrayList("John", "Jane", "Adam"));
|
||||
final String result = Joiner.on(";").join(Iterables.transform(nested, new Function<List<String>, String>() {
|
||||
@Override
|
||||
public final String apply(final List<String> input) {
|
||||
return Joiner.on("-").join(input);
|
||||
}
|
||||
}));
|
||||
|
||||
assertThat(result, containsString("apple-banana-orange"));
|
||||
assertThat(result, containsString("cat-dog-bird"));
|
||||
assertThat(result, containsString("John-Jane-Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseForNull_thenUsed() {
|
||||
final List<String> names = Lists.newArrayList("John", null, "Jane", "Adam", "Tom");
|
||||
final String result = Joiner.on(",").useForNull("nameless").join(names);
|
||||
|
||||
assertEquals(result, "John,nameless,Jane,Adam,Tom");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateListFromString_thenCreated() {
|
||||
final String input = "apple - banana - orange";
|
||||
final List<String> result = Splitter.on("-").trimResults().splitToList(input);
|
||||
|
||||
assertThat(result, contains("apple", "banana", "orange"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMapFromString_thenCreated() {
|
||||
final String input = "John=first,Adam=second";
|
||||
final Map<String, String> result = Splitter.on(",").withKeyValueSeparator("=").split(input);
|
||||
|
||||
assertEquals("first", result.get("John"));
|
||||
assertEquals("second", result.get("Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSplitStringOnMultipleSeparator_thenSplit() {
|
||||
final String input = "apple.banana,,orange,,.";
|
||||
final List<String> result = Splitter.onPattern("[.,]").omitEmptyStrings().splitToList(input);
|
||||
|
||||
assertThat(result, contains("apple", "banana", "orange"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSplitStringOnSpecificLength_thenSplit() {
|
||||
final String input = "Hello world";
|
||||
final List<String> result = Splitter.fixedLength(3).splitToList(input);
|
||||
|
||||
assertThat(result, contains("Hel", "lo ", "wor", "ld"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLimitSplitting_thenLimited() {
|
||||
final String input = "a,b,c,d,e";
|
||||
final List<String> result = Splitter.on(",").limit(4).splitToList(input);
|
||||
|
||||
assertEquals(4, result.size());
|
||||
assertThat(result, contains("a", "b", "c", "d,e"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.baeldung.guava.ordering;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Functions;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Ordering;
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
public class GuavaOrderingExamplesUnitTest {
|
||||
|
||||
private final class OrderingByLenght extends Ordering<String> {
|
||||
@Override
|
||||
public final int compare(final String s1, final String s2) {
|
||||
return Ints.compare(s1.length(), s2.length());
|
||||
}
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
// dealing with null
|
||||
|
||||
@Test
|
||||
public final void givenCollectionWithNulls_whenSortingWithNullsLast_thenNullsAreLast() {
|
||||
final List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
|
||||
Collections.sort(toSort, Ordering.natural().nullsLast());
|
||||
assertThat(toSort.get(toSort.size() - 1), nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCollectionWithNulls_whenSortingWithNullsFirst_thenNullsAreFirst() {
|
||||
final List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
|
||||
Collections.sort(toSort, Ordering.natural().nullsFirst());
|
||||
assertThat(toSort.get(0), nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCollectionIsSortedNullsLastReversed_thenNullAreFirst() {
|
||||
final List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
|
||||
Collections.sort(toSort, Ordering.natural().nullsLast().reverse());
|
||||
assertThat(toSort.get(0), nullValue());
|
||||
}
|
||||
|
||||
// natural ordering
|
||||
|
||||
@Test
|
||||
public final void whenSortingWithNaturalOrdering_thenCorectlySorted() {
|
||||
final List<Integer> toSort = Arrays.asList(3, 5, 4, 1, 2);
|
||||
Collections.sort(toSort, Ordering.natural());
|
||||
|
||||
assertTrue(Ordering.natural().isOrdered(toSort));
|
||||
}
|
||||
|
||||
// checking string ordering
|
||||
|
||||
@Test
|
||||
public final void givenCollectionContainsDuplicates_whenCheckingStringOrdering_thenNo() {
|
||||
final List<Integer> toSort = Arrays.asList(3, 5, 4, 2, 1, 2);
|
||||
Collections.sort(toSort, Ordering.natural());
|
||||
|
||||
assertFalse(Ordering.natural().isStrictlyOrdered(toSort));
|
||||
}
|
||||
|
||||
// custom - by length
|
||||
|
||||
@Test
|
||||
public final void givenCollectionIsSorted_whenUsingOrderingApiToCheckOrder_thenCheckCanBePerformed() {
|
||||
final List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
|
||||
final Ordering<String> byLength = new OrderingByLenght();
|
||||
Collections.sort(toSort, byLength);
|
||||
|
||||
final Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "zz", "aa", "ccc"));
|
||||
assertTrue(expectedOrder.isOrdered(toSort));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSortingCollectionsOfStringsByLenght_thenCorrectlySorted() {
|
||||
final List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
|
||||
final Ordering<String> byLength = new OrderingByLenght();
|
||||
|
||||
Collections.sort(toSort, byLength);
|
||||
|
||||
final Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "zz", "aa", "ccc"));
|
||||
assertTrue(expectedOrder.isOrdered(toSort));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSortingCollectionsOfStringsByLenghtWithSecondaryNaturalOrdering_thenCorrectlySorted() {
|
||||
final List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
|
||||
final Ordering<String> byLength = new OrderingByLenght();
|
||||
|
||||
Collections.sort(toSort, byLength.compound(Ordering.natural()));
|
||||
|
||||
final Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "aa", "zz", "ccc"));
|
||||
assertTrue(expectedOrder.isOrdered(toSort));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSortingCollectionsWithComplexOrderingExample_thenCorrectlySorted() {
|
||||
final List<String> toSort = Arrays.asList("zz", "aa", null, "b", "ccc");
|
||||
|
||||
Collections.sort(toSort, new OrderingByLenght().reverse().compound(Ordering.natural()).nullsLast());
|
||||
System.out.println(toSort);
|
||||
}
|
||||
|
||||
// sorted copy
|
||||
|
||||
@Test
|
||||
public final void givenUnorderdList_whenRetrievingSortedCopy_thenSorted() {
|
||||
final List<String> toSort = Arrays.asList("aa", "b", "ccc");
|
||||
final List<String> sortedCopy = new OrderingByLenght().sortedCopy(toSort);
|
||||
|
||||
final Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "aa", "ccc"));
|
||||
assertFalse(expectedOrder.isOrdered(toSort));
|
||||
assertTrue(expectedOrder.isOrdered(sortedCopy));
|
||||
}
|
||||
|
||||
// to string
|
||||
|
||||
@Test
|
||||
public final void givenUnorderdList_whenUsingToStringForSortingObjects_thenSortedWithToString() {
|
||||
final List<Integer> toSort = Arrays.asList(1, 2, 11);
|
||||
Collections.sort(toSort, Ordering.usingToString());
|
||||
|
||||
final Ordering<Integer> expectedOrder = Ordering.explicit(Lists.newArrayList(1, 11, 2));
|
||||
assertTrue(expectedOrder.isOrdered(toSort));
|
||||
}
|
||||
|
||||
// binary search
|
||||
|
||||
@Test
|
||||
public final void whenPerformingBinarySearch_thenFound() {
|
||||
final List<Integer> toSort = Arrays.asList(1, 2, 11);
|
||||
Collections.sort(toSort, Ordering.usingToString());
|
||||
final int found = Ordering.usingToString().binarySearch(toSort, 2);
|
||||
|
||||
System.out.println(found);
|
||||
}
|
||||
|
||||
// min/max without actually sorting
|
||||
|
||||
@Test
|
||||
public final void whenFindingTheMinimalElementWithoutSorting_thenFound() {
|
||||
final List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
|
||||
final int found = Ordering.natural().min(toSort);
|
||||
assertThat(found, equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindingTheFirstFewElements_thenCorrect() {
|
||||
final List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
|
||||
final List<Integer> leastOf = Ordering.natural().leastOf(toSort, 3);
|
||||
final List<Integer> expected = Lists.newArrayList(1, 2, 8);
|
||||
assertThat(expected, equalTo(leastOf));
|
||||
}
|
||||
|
||||
// order the results of a Function
|
||||
|
||||
@Test
|
||||
public final void givenListOfNumbers_whenRunningAToStringFunctionThenSorting_thenCorrect() {
|
||||
final List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
|
||||
final Ordering<Object> ordering = Ordering.natural().onResultOf(Functions.toStringFunction());
|
||||
final List<Integer> sortedCopy = ordering.sortedCopy(toSort);
|
||||
|
||||
final List<Integer> expected = Lists.newArrayList(1, 100, 11, 14, 2, 8);
|
||||
assertThat(expected, equalTo(sortedCopy));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.guava.ordering;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.collect.Ordering;
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class GuavaOrderingUnitTest {
|
||||
@Test
|
||||
public void givenListOfIntegers_whenCreateNaturalOrderOrdering_shouldSortProperly() {
|
||||
//given
|
||||
List<Integer> integers = Arrays.asList(3, 2, 1);
|
||||
|
||||
//when
|
||||
integers.sort(Ordering.natural());
|
||||
|
||||
//then
|
||||
assertEquals(Arrays.asList(1, 2, 3), integers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfPersonObject_whenSortedUsingCustomOrdering_shouldSortProperly() {
|
||||
//given
|
||||
List<Person> persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3));
|
||||
Ordering<Person> orderingByAge = new Ordering<Person>() {
|
||||
@Override
|
||||
public int compare(Person p1, Person p2) {
|
||||
return Ints.compare(p1.age, p2.age);
|
||||
}
|
||||
};
|
||||
|
||||
//when
|
||||
persons.sort(orderingByAge);
|
||||
|
||||
//then
|
||||
assertEquals(Arrays.asList(new Person("Alice", 3), new Person("Michael", 10)), persons);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfPersonObject_whenSortedUsingChainedOrdering_shouldSortPropely() {
|
||||
//given
|
||||
List<Person> persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3), new Person("Thomas", null));
|
||||
Ordering<Person> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Person, Comparable>() {
|
||||
@Override
|
||||
public Comparable apply(Person person) {
|
||||
return person.age;
|
||||
}
|
||||
});
|
||||
|
||||
//when
|
||||
persons.sort(ordering);
|
||||
|
||||
//then
|
||||
assertEquals(Arrays.asList(new Person("Thomas", null), new Person("Alice", 3), new Person("Michael", 10)), persons);
|
||||
}
|
||||
|
||||
|
||||
class Person {
|
||||
private final String name;
|
||||
private final Integer age;
|
||||
|
||||
private Person(String name, Integer age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Person person = (Person) o;
|
||||
|
||||
if (name != null ? !name.equals(person.name) : person.name != null) return false;
|
||||
return age != null ? age.equals(person.age) : person.age == null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = name != null ? name.hashCode() : 0;
|
||||
result = 31 * result + (age != null ? age.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.guava.queues;
|
||||
|
||||
|
||||
import com.google.common.collect.EvictingQueue;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Queue;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||
|
||||
public class EvictingQueueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEvictingQueue_whenAddElementToFull_thenShouldEvictOldestItem() {
|
||||
//given
|
||||
Queue<Integer> evictingQueue = EvictingQueue.create(10);
|
||||
|
||||
//when
|
||||
IntStream.range(0, 10).forEach(evictingQueue::add);
|
||||
|
||||
//then
|
||||
assertThat(evictingQueue).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
|
||||
|
||||
//and
|
||||
evictingQueue.add(100);
|
||||
|
||||
//then
|
||||
assertThat(evictingQueue).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.guava.queues;
|
||||
|
||||
|
||||
import com.google.common.collect.MinMaxPriorityQueue;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MinMaxPriorityQueueUnitTest {
|
||||
@Test
|
||||
public void givenMinMaxPriorityQueue_whenAddElementToFull_thenShouldEvictGreatestItem() {
|
||||
//given
|
||||
MinMaxPriorityQueue<CustomClass> queue = MinMaxPriorityQueue
|
||||
.orderedBy(Comparator.comparing(CustomClass::getValue))
|
||||
.maximumSize(10)
|
||||
.create();
|
||||
|
||||
//when
|
||||
IntStream
|
||||
.iterate(10, i -> i - 1)
|
||||
.limit(10)
|
||||
.forEach(i -> queue.add(new CustomClass(i)));
|
||||
|
||||
//then
|
||||
assertThat(queue.peekFirst().getValue()).isEqualTo(1);
|
||||
assertThat(queue.peekLast().getValue()).isEqualTo(10);
|
||||
|
||||
|
||||
//and
|
||||
queue.add(new CustomClass(-1));
|
||||
|
||||
|
||||
//then
|
||||
assertThat(queue.peekFirst().getValue()).isEqualTo(-1);
|
||||
assertThat(queue.peekLast().getValue()).isEqualTo(9);
|
||||
|
||||
//and
|
||||
queue.add(new CustomClass(100));
|
||||
assertThat(queue.peekFirst().getValue()).isEqualTo(-1);
|
||||
assertThat(queue.peekLast().getValue()).isEqualTo(9);
|
||||
|
||||
}
|
||||
|
||||
|
||||
class CustomClass {
|
||||
private final Integer value;
|
||||
|
||||
CustomClass(Integer value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Integer getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CustomClass{" +
|
||||
"value=" + value +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package com.baeldung.guava.table;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.ArrayTable;
|
||||
import com.google.common.collect.HashBasedTable;
|
||||
import com.google.common.collect.ImmutableTable;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Table;
|
||||
import com.google.common.collect.TreeBasedTable;
|
||||
|
||||
public class GuavaTableUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTable_whenGet_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
|
||||
final Integer seatCountForNoEntry = universityCourseSeatTable.get("Oxford", "IT");
|
||||
|
||||
assertThat(seatCount).isEqualTo(60);
|
||||
assertThat(seatCountForNoEntry).isEqualTo(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenContains_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final boolean entryIsPresent = universityCourseSeatTable.contains("Mumbai", "IT");
|
||||
final boolean entryIsAbsent = universityCourseSeatTable.contains("Oxford", "IT");
|
||||
final boolean courseIsPresent = universityCourseSeatTable.containsColumn("IT");
|
||||
final boolean universityIsPresent = universityCourseSeatTable.containsRow("Mumbai");
|
||||
final boolean seatCountIsPresent = universityCourseSeatTable.containsValue(60);
|
||||
|
||||
assertThat(entryIsPresent).isEqualTo(true);
|
||||
assertThat(entryIsAbsent).isEqualTo(false);
|
||||
assertThat(courseIsPresent).isEqualTo(true);
|
||||
assertThat(universityIsPresent).isEqualTo(true);
|
||||
assertThat(seatCountIsPresent).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenRemove_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
|
||||
final int seatCount = universityCourseSeatTable.remove("Mumbai", "IT");
|
||||
|
||||
assertThat(seatCount).isEqualTo(60);
|
||||
assertThat(universityCourseSeatTable.remove("Mumbai", "IT")).isEqualTo(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenColumn_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final Map<String, Integer> universitySeatMap = universityCourseSeatTable.column("IT");
|
||||
|
||||
assertThat(universitySeatMap).hasSize(2);
|
||||
assertThat(universitySeatMap.get("Mumbai")).isEqualTo(60);
|
||||
assertThat(universitySeatMap.get("Harvard")).isEqualTo(120);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenColumnMap_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final Map<String, Map<String, Integer>> courseKeyUniversitySeatMap = universityCourseSeatTable.columnMap();
|
||||
|
||||
assertThat(courseKeyUniversitySeatMap).hasSize(3);
|
||||
assertThat(courseKeyUniversitySeatMap.get("IT")).hasSize(2);
|
||||
assertThat(courseKeyUniversitySeatMap.get("Electrical")).hasSize(1);
|
||||
assertThat(courseKeyUniversitySeatMap.get("Chemical")).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenRow_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final Map<String, Integer> courseSeatMap = universityCourseSeatTable.row("Mumbai");
|
||||
|
||||
assertThat(courseSeatMap).hasSize(2);
|
||||
assertThat(courseSeatMap.get("IT")).isEqualTo(60);
|
||||
assertThat(courseSeatMap.get("Chemical")).isEqualTo(120);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenRowKeySet_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final Set<String> universitySet = universityCourseSeatTable.rowKeySet();
|
||||
|
||||
assertThat(universitySet).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenColKeySet_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final Set<String> courseSet = universityCourseSeatTable.columnKeySet();
|
||||
|
||||
assertThat(courseSet).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeTable_whenGet_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = TreeBasedTable.create();
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
|
||||
|
||||
assertThat(seatCount).isEqualTo(60);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableTable_whenGet_returnsSuccessfully() {
|
||||
final Table<String, String, Integer> universityCourseSeatTable = ImmutableTable.<String, String, Integer> builder()
|
||||
.put("Mumbai", "Chemical", 120)
|
||||
.put("Mumbai", "IT", 60)
|
||||
.put("Harvard", "Electrical", 60)
|
||||
.put("Harvard", "IT", 120)
|
||||
.build();
|
||||
|
||||
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
|
||||
|
||||
assertThat(seatCount).isEqualTo(60);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayTable_whenGet_returnsSuccessfully() {
|
||||
final List<String> universityRowTable = Lists.newArrayList("Mumbai", "Harvard");
|
||||
final List<String> courseColumnTables = Lists.newArrayList("Chemical", "IT", "Electrical");
|
||||
final Table<String, String, Integer> universityCourseSeatTable = ArrayTable.create(universityRowTable, courseColumnTables);
|
||||
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
|
||||
universityCourseSeatTable.put("Mumbai", "IT", 60);
|
||||
universityCourseSeatTable.put("Harvard", "Electrical", 60);
|
||||
universityCourseSeatTable.put("Harvard", "IT", 120);
|
||||
|
||||
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
|
||||
|
||||
assertThat(seatCount).isEqualTo(60);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.baeldung.hamcrest;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.Matchers.emptyArray;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.everyItem;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.Matchers.emptyIterable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
public class HamcrestExamplesUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingSingleElementIsPartOfCollection_thenCorrect() {
|
||||
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
|
||||
assertThat(collection, hasItem("cd"));
|
||||
assertThat(collection, not(hasItem("zz")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingMultipleElementsArePartOfCollection_thenCorrect1() {
|
||||
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
|
||||
assertThat(collection, hasItems("ef", "cd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingMultipleElementsArePartOfCollectionInStrictOrder_thenCorrect2() {
|
||||
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
|
||||
assertThat(collection, contains("ab", "cd", "ef"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingMultipleElementsArePartOfCollectionInAnyOrder_thenCorrect2() {
|
||||
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
|
||||
assertThat(collection, containsInAnyOrder("cd", "ab", "ef"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCollectionIsEmpty_whenChecking_thenEmpty() {
|
||||
final List<String> collection = Lists.newArrayList();
|
||||
assertThat(collection, empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIterableIsEmpty_whenChecking_thenEmpty() {
|
||||
final Iterable<String> collection = Lists.newArrayList();
|
||||
assertThat(collection, emptyIterable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCollectionIsNotEmpty_whenChecking_thenNotEmpty() {
|
||||
final List<String> collection = Lists.newArrayList("a");
|
||||
assertThat(collection, not(empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenMapIsEmpty_whenChecking_thenEmpty() {
|
||||
final Map<String, String> collection = Maps.newHashMap();
|
||||
assertThat(collection, equalTo(Collections.EMPTY_MAP));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenArrayIsEmpty_whenChecking_thenEmpty() {
|
||||
final String[] array = new String[] { "ab" };
|
||||
assertThat(array, not(emptyArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCollectionSizeIsChecked_thenCorrect() {
|
||||
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
|
||||
assertThat(collection, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenIterableSizeIsChecked_thenCorrect() {
|
||||
final Iterable<String> collection = Lists.newArrayList("ab", "cd", "ef");
|
||||
assertThat(collection, Matchers.<String> iterableWithSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCheckingConditionOverEachItem_thenCorrect() {
|
||||
final List<Integer> collection = Lists.newArrayList(15, 20, 25, 30);
|
||||
assertThat(collection, everyItem(greaterThan(10)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
John Jane Adam Tom
|
||||
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
@@ -0,0 +1 @@
|
||||
Test
|
||||
@@ -0,0 +1,4 @@
|
||||
John
|
||||
Jane
|
||||
Adam
|
||||
Tom
|
||||
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
BIN
guava-modules/guava-collections/src/test/resources/test_le.txt
Normal file
BIN
guava-modules/guava-collections/src/test/resources/test_le.txt
Normal file
Binary file not shown.
10
guava-modules/guava-core/README.md
Normal file
10
guava-modules/guava-core/README.md
Normal file
@@ -0,0 +1,10 @@
|
||||
## Guava Core
|
||||
|
||||
This module contains articles about core or base functionality provided by Google Guava
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables)
|
||||
- [Guava CharMatcher](https://www.baeldung.com/guava-string-charmatcher)
|
||||
- [Guide to Guava’s PreConditions](https://www.baeldung.com/guava-preconditions)
|
||||
- [Introduction to Guava Memoizer](https://www.baeldung.com/guava-memoizer)
|
||||
- [Guava Functional Cookbook](https://www.baeldung.com/guava-functions-predicates)
|
||||
48
guava-modules/guava-core/pom.xml
Normal file
48
guava-modules/guava-core/pom.xml
Normal file
@@ -0,0 +1,48 @@
|
||||
<?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-core</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>guava-core</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.guava.memoizer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class CostlySupplier {
|
||||
|
||||
public static BigInteger generateBigNumber() {
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
return new BigInteger("12345");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.guava.memoizer;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class Factorial {
|
||||
|
||||
private static LoadingCache<Integer, BigInteger> memo = CacheBuilder.newBuilder()
|
||||
.build(CacheLoader.from(Factorial::getFactorial));
|
||||
|
||||
public static BigInteger getFactorial(int n) {
|
||||
if (n == 0) {
|
||||
return BigInteger.ONE;
|
||||
} else {
|
||||
return BigInteger.valueOf(n).multiply(memo.getUnchecked(n - 1));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.guava.memoizer;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class FibonacciSequence {
|
||||
|
||||
private static LoadingCache<Integer, BigInteger> memo = CacheBuilder.newBuilder()
|
||||
.maximumSize(100)
|
||||
.build(CacheLoader.from(FibonacciSequence::getFibonacciNumber));
|
||||
|
||||
public static BigInteger getFibonacciNumber(int n) {
|
||||
if (n == 0) {
|
||||
return BigInteger.ZERO;
|
||||
} else if (n == 1) {
|
||||
return BigInteger.ONE;
|
||||
} else {
|
||||
return memo.getUnchecked(n - 1).add(memo.getUnchecked(n - 2));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.baeldung.guava.charmatcher;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetEncoder;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.common.base.Predicate;
|
||||
|
||||
public class GuavaCharMatcherUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenRemoveSpecialCharacters_thenRemoved() {
|
||||
final String input = "H*el.lo,}12";
|
||||
final CharMatcher matcher = CharMatcher.javaLetterOrDigit();
|
||||
final String result = matcher.retainFrom(input);
|
||||
|
||||
assertEquals("Hello12", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveNonASCIIChars_thenRemoved() {
|
||||
final String input = "あhello₤";
|
||||
|
||||
String result = CharMatcher.ascii().retainFrom(input);
|
||||
assertEquals("hello", result);
|
||||
|
||||
result = CharMatcher.inRange('0', 'z').retainFrom(input);
|
||||
assertEquals("hello", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidateString_thenValid() {
|
||||
final String input = "hello";
|
||||
|
||||
boolean result = CharMatcher.javaLowerCase().matchesAllOf(input);
|
||||
assertTrue(result);
|
||||
|
||||
result = CharMatcher.is('e').matchesAnyOf(input);
|
||||
assertTrue(result);
|
||||
|
||||
result = CharMatcher.javaDigit().matchesNoneOf(input);
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTrimString_thenTrimmed() {
|
||||
final String input = "---hello,,,";
|
||||
|
||||
String result = CharMatcher.is('-').trimLeadingFrom(input);
|
||||
assertEquals("hello,,,", result);
|
||||
|
||||
result = CharMatcher.is(',').trimTrailingFrom(input);
|
||||
assertEquals("---hello", result);
|
||||
|
||||
result = CharMatcher.anyOf("-,").trimFrom(input);
|
||||
assertEquals("hello", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollapseFromString_thenCollapsed() {
|
||||
final String input = " hel lo ";
|
||||
|
||||
String result = CharMatcher.is(' ').collapseFrom(input, '-');
|
||||
assertEquals("-hel-lo-", result);
|
||||
|
||||
result = CharMatcher.is(' ').trimAndCollapseFrom(input, '-');
|
||||
assertEquals("hel-lo", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceFromString_thenReplaced() {
|
||||
final String input = "apple-banana.";
|
||||
|
||||
String result = CharMatcher.anyOf("-.").replaceFrom(input, '!');
|
||||
assertEquals("apple!banana!", result);
|
||||
|
||||
result = CharMatcher.is('-').replaceFrom(input, " and ");
|
||||
assertEquals("apple and banana.", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCountCharInString_thenCorrect() {
|
||||
final String input = "a, c, z, 1, 2";
|
||||
|
||||
int result = CharMatcher.is(',').countIn(input);
|
||||
assertEquals(4, result);
|
||||
|
||||
result = CharMatcher.inRange('a', 'h').countIn(input);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveCharsNotInCharset_thenRemoved() {
|
||||
final Charset charset = Charset.forName("cp437");
|
||||
final CharsetEncoder encoder = charset.newEncoder();
|
||||
|
||||
final Predicate<Character> inRange = new Predicate<Character>() {
|
||||
@Override
|
||||
public boolean apply(final Character c) {
|
||||
return encoder.canEncode(c);
|
||||
}
|
||||
};
|
||||
|
||||
final String result = CharMatcher.forPredicate(inRange).retainFrom("helloは");
|
||||
assertEquals("hello", result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.baeldung.guava.functional;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.lessThan;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Functions;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Predicates;
|
||||
import com.google.common.collect.Collections2;
|
||||
import com.google.common.collect.FluentIterable;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Ordering;
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
public class GuavaFunctionalExamplesUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
// predicates - filtering
|
||||
|
||||
@Test
|
||||
public final void whenFilteringNumbersAccordingToACondition_thenCorrectResults() {
|
||||
final List<Integer> numbers = Lists.newArrayList(1, 2, 3, 6, 8, 10, 34, 57, 89);
|
||||
final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
|
||||
@Override
|
||||
public final boolean apply(final Integer number) {
|
||||
return (number % 2) == 0;
|
||||
}
|
||||
};
|
||||
final List<Integer> evenNumbers = Lists.newArrayList(Collections2.filter(numbers, acceptEvenNumber));
|
||||
|
||||
final Integer found = Collections.binarySearch(evenNumbers, 57);
|
||||
assertThat(found, lessThan(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCollectionContainsNulls_whenNullsAreFilteredOut_thenResultingCollectionsHasNoNulls() {
|
||||
final List<String> withNulls = Lists.newArrayList("a", "bc", null, "def");
|
||||
final Iterable<String> withoutNuls = Iterables.filter(withNulls, Predicates.notNull());
|
||||
|
||||
assertTrue(Iterables.all(withoutNuls, Predicates.notNull()));
|
||||
}
|
||||
|
||||
// predicates - checking
|
||||
|
||||
@Test
|
||||
public final void givenEvenNumbers_whenCheckingIfAllSatisfyTheEvenPredicate_thenYes() {
|
||||
final List<Integer> evenNumbers = Lists.newArrayList(2, 6, 8, 10, 34, 90);
|
||||
final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
|
||||
@Override
|
||||
public final boolean apply(final Integer number) {
|
||||
return (number % 2) == 0;
|
||||
}
|
||||
};
|
||||
|
||||
assertTrue(Iterables.all(evenNumbers, acceptEvenNumber));
|
||||
}
|
||||
|
||||
// negating a predicate
|
||||
|
||||
@Test
|
||||
public final void givenCollectionOfEvenNumbers_whenCheckingThatCollectionContainsNoOddNumber_thenTrue() {
|
||||
final List<Integer> evenNumbers = Lists.newArrayList(2, 6, 8, 10, 34, 90);
|
||||
final Predicate<Integer> acceptOddNumber = new Predicate<Integer>() {
|
||||
@Override
|
||||
public final boolean apply(final Integer number) {
|
||||
return (number % 2) != 0;
|
||||
}
|
||||
};
|
||||
|
||||
assertTrue(Iterables.all(evenNumbers, Predicates.not(acceptOddNumber)));
|
||||
}
|
||||
|
||||
// other predicates
|
||||
|
||||
@Test
|
||||
public final void when_thenCorrect() {
|
||||
// CharMatcher.forPredicate(predicate)
|
||||
}
|
||||
|
||||
// functions
|
||||
|
||||
@Test
|
||||
public final void whenApplyingSimpleFunctionToInputs_thenCorrectlyTransformed() {
|
||||
final List<Integer> numbers = Lists.newArrayList(1, 2, 3);
|
||||
final List<String> numbersAsStrings = Lists.transform(numbers, Functions.toStringFunction());
|
||||
assertThat(numbersAsStrings, contains("1", "2", "3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenUsingAnIntermediaryFunctionToOrder_thenCorerctlyOrderedInAlphabeticalOrder() {
|
||||
final List<Integer> numbersToSort = Arrays.asList(2, 1, 11, 100, 8, 14);
|
||||
final Ordering<Object> ordering = Ordering.natural().onResultOf(Functions.toStringFunction());
|
||||
final List<Integer> inAlphabeticalOrder = ordering.sortedCopy(numbersToSort);
|
||||
|
||||
final List<Integer> correctAlphabeticalOrder = Lists.newArrayList(1, 100, 11, 14, 2, 8);
|
||||
assertThat(correctAlphabeticalOrder, equalTo(inAlphabeticalOrder));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenChainingPredicatesAndFunctions_thenCorrectResults() {
|
||||
final List<Integer> numbers = Arrays.asList(2, 1, 11, 100, 8, 14);
|
||||
final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
|
||||
@Override
|
||||
public final boolean apply(final Integer number) {
|
||||
return (number % 2) == 0;
|
||||
}
|
||||
};
|
||||
final Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final Integer input) {
|
||||
return (int) Math.pow(input, 2);
|
||||
}
|
||||
};
|
||||
|
||||
final FluentIterable<Integer> powerOfTwoOnlyForEvenNumbers = FluentIterable.from(numbers).filter(acceptEvenNumber).transform(powerOfTwo);
|
||||
assertThat(powerOfTwoOnlyForEvenNumbers, contains(4, 10000, 64, 196));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenUsingFunctionComposition_thenCorrectResults() {
|
||||
final List<Integer> numbers = Arrays.asList(2, 3);
|
||||
final Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final Integer input) {
|
||||
return (int) Math.pow(input, 2);
|
||||
}
|
||||
};
|
||||
|
||||
final List<Integer> result = Lists.transform(numbers, Functions.compose(powerOfTwo, powerOfTwo));
|
||||
assertThat(result, contains(16, 81));
|
||||
}
|
||||
|
||||
// Set+Function => Map
|
||||
|
||||
/**
|
||||
* - see: http://code.google.com/p/guava-libraries/issues/detail?id=56
|
||||
*/
|
||||
@Test
|
||||
public final void whenMapIsBackedBySetAndFunction_thenCorrect() {
|
||||
final Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final Integer input) {
|
||||
return (int) Math.pow(input, 2);
|
||||
}
|
||||
};
|
||||
final Set<Integer> lowNumbers = Sets.newHashSet(2, 3, 4);
|
||||
|
||||
final Map<Integer, Integer> numberToPowerOfTwoMuttable = Maps.asMap(lowNumbers, powerOfTwo);
|
||||
final Map<Integer, Integer> numberToPowerOfTwoImuttable = Maps.toMap(lowNumbers, powerOfTwo);
|
||||
assertThat(numberToPowerOfTwoMuttable.get(2), equalTo(4));
|
||||
assertThat(numberToPowerOfTwoImuttable.get(2), equalTo(4));
|
||||
}
|
||||
|
||||
// Predicate => Function
|
||||
|
||||
@Test
|
||||
public final void whenConvertingPredicateToFunction_thenCorrect() {
|
||||
final List<Integer> numbers = Lists.newArrayList(1, 2, 3, 6);
|
||||
final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
|
||||
@Override
|
||||
public final boolean apply(final Integer number) {
|
||||
return (number % 2) == 0;
|
||||
}
|
||||
};
|
||||
final Function<Integer, Boolean> isEventNumberFunction = Functions.forPredicate(acceptEvenNumber);
|
||||
final List<Boolean> areNumbersEven = Lists.transform(numbers, isEventNumberFunction);
|
||||
|
||||
assertThat(areNumbersEven, contains(false, true, false, true));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.baeldung.guava.memoizer;
|
||||
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.baeldung.guava.memoizer.CostlySupplier;
|
||||
import com.baeldung.guava.memoizer.Factorial;
|
||||
import com.baeldung.guava.memoizer.FibonacciSequence;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.hamcrest.number.IsCloseTo.closeTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class GuavaMemoizerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInteger_whenGetFibonacciNumber_thenShouldCalculateFibonacciNumber() {
|
||||
// given
|
||||
int n = 95;
|
||||
|
||||
// when
|
||||
BigInteger fibonacciNumber = FibonacciSequence.getFibonacciNumber(n);
|
||||
|
||||
// then
|
||||
BigInteger expectedFibonacciNumber = new BigInteger("31940434634990099905");
|
||||
assertThat(fibonacciNumber, is(equalTo(expectedFibonacciNumber)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInteger_whenGetFactorial_thenShouldCalculateFactorial() {
|
||||
// given
|
||||
int n = 95;
|
||||
|
||||
// when
|
||||
BigInteger factorial = Factorial.getFactorial(n);
|
||||
|
||||
// then
|
||||
BigInteger expectedFactorial = new BigInteger("10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000");
|
||||
assertThat(factorial, is(equalTo(expectedFactorial)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMemoizedSupplier_whenGet_thenSubsequentGetsAreFast() {
|
||||
// given
|
||||
Supplier<BigInteger> memoizedSupplier;
|
||||
memoizedSupplier = Suppliers.memoize(CostlySupplier::generateBigNumber);
|
||||
|
||||
// when
|
||||
BigInteger expectedValue = new BigInteger("12345");
|
||||
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 2000D);
|
||||
|
||||
// then
|
||||
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 0D);
|
||||
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 0D);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMemoizedSupplierWithExpiration_whenGet_thenSubsequentGetsBeforeExpiredAreFast() throws InterruptedException {
|
||||
// given
|
||||
Supplier<BigInteger> memoizedSupplier;
|
||||
memoizedSupplier = Suppliers.memoizeWithExpiration(CostlySupplier::generateBigNumber, 3, TimeUnit.SECONDS);
|
||||
|
||||
// when
|
||||
BigInteger expectedValue = new BigInteger("12345");
|
||||
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 2000D);
|
||||
|
||||
// then
|
||||
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 0D);
|
||||
// add one more second until memoized Supplier is evicted from memory
|
||||
TimeUnit.SECONDS.sleep(3);
|
||||
assertSupplierGetExecutionResultAndDuration(memoizedSupplier, expectedValue, 2000D);
|
||||
}
|
||||
|
||||
private <T> void assertSupplierGetExecutionResultAndDuration(Supplier<T> supplier,
|
||||
T expectedValue,
|
||||
double expectedDurationInMs) {
|
||||
Instant start = Instant.now();
|
||||
T value = supplier.get();
|
||||
Long durationInMs = Duration.between(start, Instant.now()).toMillis();
|
||||
double marginOfErrorInMs = 100D;
|
||||
|
||||
assertThat(value, is(equalTo(expectedValue)));
|
||||
assertThat(durationInMs.doubleValue(), is(closeTo(expectedDurationInMs, marginOfErrorInMs)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.baeldung.guava.preconditions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import java.util.Arrays;
|
||||
import org.junit.Test;
|
||||
import com.google.common.base.*;
|
||||
|
||||
public class GuavaPreConditionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCheckArgumentEvaluatesFalse_throwsException() {
|
||||
int age = -18;
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0)).isInstanceOf(IllegalArgumentException.class).hasMessage(null).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() {
|
||||
final int age = -18;
|
||||
final String message = "Age can't be zero or less than zero";
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message)).isInstanceOf(IllegalArgumentException.class).hasMessage(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTemplatedErrorMessage_whenCheckArgumentEvaluatesFalse_throwsException() {
|
||||
final int age = -18;
|
||||
final String message = "Age can't be zero or less than zero, you supplied %s.";
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message, age)).isInstanceOf(IllegalArgumentException.class).hasMessage(message, age).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() {
|
||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegersAndMessage_whenCheckElementIndexEvaluatesFalse_throwsException() {
|
||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
final String message = "Please check the bound of an array and retry";
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullString_whenCheckNotNullCalledWithMessage_throwsException() {
|
||||
final String nullObject = null;
|
||||
final String message = "Please check the Object supplied, its null!";
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message)).isInstanceOf(NullPointerException.class).hasMessage(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullString_whenCheckNotNullCalledWithTemplatedMessage_throwsException() {
|
||||
final String nullObject = null;
|
||||
final String message = "Please check the Object supplied, its %s!";
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, new Object[] { null })).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() {
|
||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegersAndMessage_whenCheckPositionIndexEvaluatesFalse_throwsException() {
|
||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
final String message = "Please check the bound of an array and retry";
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() {
|
||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkPositionIndexes(6, 0, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidStatesAndMessage_whenCheckStateEvaluatesFalse_throwsException() {
|
||||
final int[] validStates = { -1, 0, 1 };
|
||||
final int givenState = 10;
|
||||
final String message = "You have entered an invalid state";
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message)).isInstanceOf(IllegalStateException.class).hasMessageStartingWith(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidStatesAndTemplatedMessage_whenCheckStateEvaluatesFalse_throwsException() {
|
||||
final int[] validStates = { -1, 0, 1 };
|
||||
final int givenState = 10;
|
||||
final String message = "State can't be %s, It can be one of %s.";
|
||||
|
||||
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))).isInstanceOf(IllegalStateException.class)
|
||||
.hasMessage(message, givenState, Arrays.toString(validStates)).hasNoCause();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.guava.throwables;
|
||||
|
||||
import com.google.common.base.Throwables;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ThrowablesUnitTest {
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void whenThrowable_shouldWrapItInRuntimeException() throws Exception {
|
||||
try {
|
||||
throwThrowable(Throwable::new);
|
||||
} catch (Throwable t) {
|
||||
Throwables.propagateIfPossible(t, Exception.class);
|
||||
throw new RuntimeException(t);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = Error.class)
|
||||
public void whenError_shouldPropagateAsIs() throws Exception {
|
||||
try {
|
||||
throwThrowable(Error::new);
|
||||
} catch (Throwable t) {
|
||||
Throwables.propagateIfPossible(t, Exception.class);
|
||||
throw new RuntimeException(t);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void whenException_shouldPropagateAsIs() throws Exception {
|
||||
try {
|
||||
throwThrowable(Exception::new);
|
||||
} catch (Throwable t) {
|
||||
Throwables.propagateIfPossible(t, Exception.class);
|
||||
throw new RuntimeException(t);
|
||||
}
|
||||
}
|
||||
|
||||
private <T extends Throwable> void throwThrowable(Supplier<T> exceptionSupplier) throws Throwable {
|
||||
throw exceptionSupplier.get();
|
||||
}
|
||||
|
||||
}
|
||||
13
guava-modules/guava-core/src/test/resources/.gitignore
vendored
Normal file
13
guava-modules/guava-core/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
1
guava-modules/guava-core/src/test/resources/test.out
Normal file
1
guava-modules/guava-core/src/test/resources/test.out
Normal file
@@ -0,0 +1 @@
|
||||
John Jane Adam Tom
|
||||
1
guava-modules/guava-core/src/test/resources/test1.in
Normal file
1
guava-modules/guava-core/src/test/resources/test1.in
Normal file
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
1
guava-modules/guava-core/src/test/resources/test1_1.in
Normal file
1
guava-modules/guava-core/src/test/resources/test1_1.in
Normal file
@@ -0,0 +1 @@
|
||||
Test
|
||||
4
guava-modules/guava-core/src/test/resources/test2.in
Normal file
4
guava-modules/guava-core/src/test/resources/test2.in
Normal file
@@ -0,0 +1,4 @@
|
||||
John
|
||||
Jane
|
||||
Adam
|
||||
Tom
|
||||
1
guava-modules/guava-core/src/test/resources/test_copy.in
Normal file
1
guava-modules/guava-core/src/test/resources/test_copy.in
Normal file
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
BIN
guava-modules/guava-core/src/test/resources/test_le.txt
Normal file
BIN
guava-modules/guava-core/src/test/resources/test_le.txt
Normal file
Binary file not shown.
8
guava-modules/guava-io/README.md
Normal file
8
guava-modules/guava-io/README.md
Normal file
@@ -0,0 +1,8 @@
|
||||
## Guava IO
|
||||
|
||||
This module contains articles about input/output (IO) with Google Guava
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Using Guava CountingOutputStream](https://www.baeldung.com/guava-counting-outputstream)
|
||||
- [Guava – Write to File, Read from File](https://www.baeldung.com/guava-write-to-file-read-from-file)
|
||||
53
guava-modules/guava-io/pom.xml
Normal file
53
guava-modules/guava-io/pom.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<?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-io</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<properties>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
<name>guava-io</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava-io</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.guava;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.io.CountingOutputStream;
|
||||
|
||||
public class GuavaCountingOutputStreamUnitTest {
|
||||
public static final int MAX = 5;
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void givenData_whenCountReachesLimit_thenThrowException() throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
CountingOutputStream cos = new CountingOutputStream(out);
|
||||
|
||||
byte[] data = new byte[1024];
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(data);
|
||||
|
||||
int b;
|
||||
while ((b = in.read()) != -1) {
|
||||
cos.write(b);
|
||||
if (cos.getCount() >= MAX) {
|
||||
throw new RuntimeException("Write limit reached");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package com.baeldung.guava;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.io.ByteSink;
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.CharSink;
|
||||
import com.google.common.io.CharSource;
|
||||
import com.google.common.io.CharStreams;
|
||||
import com.google.common.io.Files;
|
||||
import com.google.common.io.LittleEndianDataInputStream;
|
||||
import com.google.common.io.LittleEndianDataOutputStream;
|
||||
import com.google.common.io.Resources;
|
||||
|
||||
public class GuavaIOUnitTest {
|
||||
|
||||
@After
|
||||
public void afterEach() throws Exception {
|
||||
deleteProducedFiles();
|
||||
}
|
||||
|
||||
private void deleteProducedFiles() throws IOException {
|
||||
deleteIfExists("test.out");
|
||||
deleteIfExists("test_copy.in");
|
||||
deleteIfExists("test_le.txt");
|
||||
}
|
||||
|
||||
private void deleteIfExists(String fileName) throws IOException {
|
||||
java.nio.file.Files.deleteIfExists(Paths.get("src", "test", "resources", fileName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteUsingFiles_thenWritten() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
final File file = new File("src/test/resources/test.out");
|
||||
|
||||
Files.write(expectedValue, file, Charsets.UTF_8);
|
||||
|
||||
final String result = Files.toString(file, Charsets.UTF_8);
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteUsingCharSink_thenWritten() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
final File file = new File("src/test/resources/test.out");
|
||||
final CharSink sink = Files.asCharSink(file, Charsets.UTF_8);
|
||||
|
||||
sink.write(expectedValue);
|
||||
|
||||
final String result = Files.toString(file, Charsets.UTF_8);
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteMultipleLinesUsingCharSink_thenWritten() throws IOException {
|
||||
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
|
||||
final File file = new File("src/test/resources/test.out");
|
||||
final CharSink sink = Files.asCharSink(file, Charsets.UTF_8);
|
||||
|
||||
sink.writeLines(names, " ");
|
||||
|
||||
final String result = Files.toString(file, Charsets.UTF_8);
|
||||
final String expectedValue = Joiner.on(" ").join(names);
|
||||
assertEquals(expectedValue, result.trim());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteUsingByteSink_thenWritten() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
final File file = new File("src/test/resources/test.out");
|
||||
final ByteSink sink = Files.asByteSink(file);
|
||||
|
||||
sink.write(expectedValue.getBytes());
|
||||
|
||||
final String result = Files.toString(file, Charsets.UTF_8);
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUsingFiles_thenRead() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
final File file = new File("src/test/resources/test1.in");
|
||||
|
||||
final String result = Files.toString(file, Charsets.UTF_8);
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadMultipleLinesUsingFiles_thenRead() throws IOException {
|
||||
final File file = new File("src/test/resources/test2.in");
|
||||
|
||||
final List<String> result = Files.readLines(file, Charsets.UTF_8);
|
||||
assertThat(result, contains("John", "Jane", "Adam", "Tom"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUsingCharSource_thenRead() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
final File file = new File("src/test/resources/test1.in");
|
||||
|
||||
final CharSource source = Files.asCharSource(file, Charsets.UTF_8);
|
||||
|
||||
final String result = source.read();
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadMultipleCharSources_thenRead() throws IOException {
|
||||
final String expectedValue = "Hello worldTest";
|
||||
final File file1 = new File("src/test/resources/test1.in");
|
||||
final File file2 = new File("src/test/resources/test1_1.in");
|
||||
|
||||
final CharSource source1 = Files.asCharSource(file1, Charsets.UTF_8);
|
||||
final CharSource source2 = Files.asCharSource(file2, Charsets.UTF_8);
|
||||
final CharSource source = CharSource.concat(source1, source2);
|
||||
|
||||
final String result = source.read();
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUsingCharStream_thenRead() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
|
||||
final FileReader reader = new FileReader("src/test/resources/test1.in");
|
||||
final String result = CharStreams.toString(reader);
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUsingByteSource_thenRead() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
final File file = new File("src/test/resources/test1.in");
|
||||
|
||||
final ByteSource source = Files.asByteSource(file);
|
||||
|
||||
final byte[] result = source.read();
|
||||
assertEquals(expectedValue, new String(result));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadAfterOffsetUsingByteSource_thenRead() throws IOException {
|
||||
final String expectedValue = "lo world";
|
||||
final File file = new File("src/test/resources/test1.in");
|
||||
|
||||
final long offset = 3;
|
||||
final long length = 1000;
|
||||
final ByteSource source = Files.asByteSource(file).slice(offset, length);
|
||||
|
||||
final byte[] result = source.read();
|
||||
assertEquals(expectedValue, new String(result));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUsingByteStream_thenRead() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
|
||||
final FileInputStream reader = new FileInputStream("src/test/resources/test1.in");
|
||||
final byte[] result = ByteStreams.toByteArray(reader);
|
||||
|
||||
assertEquals(expectedValue, new String(result));
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUsingResources_thenRead() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
|
||||
final URL url = Resources.getResource("test1.in");
|
||||
final String result = Resources.toString(url, Charsets.UTF_8);
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCopyFileUsingFiles_thenCopied() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
|
||||
final File file1 = new File("src/test/resources/test1.in");
|
||||
final File file2 = new File("src/test/resources/test_copy.in");
|
||||
|
||||
Files.copy(file1, file2);
|
||||
final String result = Files.toString(file2, Charsets.UTF_8);
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteReadLittleEndian_thenCorrect() throws IOException {
|
||||
final int value = 100;
|
||||
|
||||
final LittleEndianDataOutputStream writer = new LittleEndianDataOutputStream(new FileOutputStream("src/test/resources/test_le.txt"));
|
||||
writer.writeInt(value);
|
||||
writer.close();
|
||||
|
||||
final LittleEndianDataInputStream reader = new LittleEndianDataInputStream(new DataInputStream(new FileInputStream("src/test/resources/test_le.txt")));
|
||||
final int result = reader.readInt();
|
||||
reader.close();
|
||||
|
||||
assertEquals(value, result);
|
||||
}
|
||||
}
|
||||
1
guava-modules/guava-io/src/test/resources/test1.in
Normal file
1
guava-modules/guava-io/src/test/resources/test1.in
Normal file
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
1
guava-modules/guava-io/src/test/resources/test1_1.in
Normal file
1
guava-modules/guava-io/src/test/resources/test1_1.in
Normal file
@@ -0,0 +1 @@
|
||||
Test
|
||||
4
guava-modules/guava-io/src/test/resources/test2.in
Normal file
4
guava-modules/guava-io/src/test/resources/test2.in
Normal file
@@ -0,0 +1,4 @@
|
||||
John
|
||||
Jane
|
||||
Adam
|
||||
Tom
|
||||
13
guava-modules/guava-utilities/.gitignore
vendored
Normal file
13
guava-modules/guava-utilities/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
12
guava-modules/guava-utilities/README.md
Normal file
12
guava-modules/guava-utilities/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
## Guava Utilities
|
||||
|
||||
This module contains articles about utilities provided by Google Guava
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to Guava CacheLoader](https://www.baeldung.com/guava-cacheloader)
|
||||
- [Guide to Guava’s EventBus](https://www.baeldung.com/guava-eventbus)
|
||||
- [Guide to Guava’s Reflection Utilities](https://www.baeldung.com/guava-reflection)
|
||||
- [Guide to Mathematical Utilities in Guava](https://www.baeldung.com/guava-math)
|
||||
- [Bloom Filter in Java using Guava](https://www.baeldung.com/guava-bloom-filter)
|
||||
- [Quick Guide to the Guava RateLimiter](https://www.baeldung.com/guava-rate-limiter)
|
||||
- [Guava Cache](https://www.baeldung.com/guava-cache)
|
||||
71
guava-modules/guava-utilities/pom.xml
Normal file
71
guava-modules/guava-utilities/pom.xml
Normal file
@@ -0,0 +1,71 @@
|
||||
<?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-utilities</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>guava-utilities</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>guava-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>guava</finalName>
|
||||
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.guava.eventbus;
|
||||
|
||||
public class CustomEvent {
|
||||
private String action;
|
||||
|
||||
CustomEvent(String action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public void setAction(String action) {
|
||||
this.action = action;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.guava.eventbus;
|
||||
|
||||
import com.google.common.eventbus.DeadEvent;
|
||||
import com.google.common.eventbus.Subscribe;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class EventListener {
|
||||
|
||||
private static int eventsHandled;
|
||||
private static final Logger LOG = LoggerFactory.getLogger(EventListener.class);
|
||||
|
||||
@Subscribe
|
||||
public void stringEvent(String event) {
|
||||
LOG.info("do event [" + event + "]");
|
||||
eventsHandled++;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void someCustomEvent(CustomEvent customEvent) {
|
||||
LOG.info("do event [" + customEvent.getAction() + "]");
|
||||
eventsHandled++;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void handleDeadEvent(DeadEvent deadEvent) {
|
||||
LOG.info("unhandled event [" + deadEvent.getEvent() + "]");
|
||||
eventsHandled++;
|
||||
}
|
||||
|
||||
int getEventsHandled() {
|
||||
return eventsHandled;
|
||||
}
|
||||
|
||||
void resetEventsHandled() {
|
||||
eventsHandled = 0;
|
||||
}
|
||||
}
|
||||
19
guava-modules/guava-utilities/src/main/resources/logback.xml
Normal file
19
guava-modules/guava-utilities/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,19 @@
|
||||
<?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>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.guava.bloomfilter;
|
||||
|
||||
|
||||
import com.google.common.hash.BloomFilter;
|
||||
import com.google.common.hash.Funnels;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class BloomFilterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() {
|
||||
//when
|
||||
BloomFilter<Integer> filter = BloomFilter.create(
|
||||
Funnels.integerFunnel(),
|
||||
500,
|
||||
0.01);
|
||||
|
||||
//when
|
||||
filter.put(1);
|
||||
filter.put(2);
|
||||
filter.put(3);
|
||||
|
||||
//then
|
||||
// the probability that it returns true, but is actually false is 1%
|
||||
assertThat(filter.mightContain(1)).isTrue();
|
||||
assertThat(filter.mightContain(2)).isTrue();
|
||||
assertThat(filter.mightContain(3)).isTrue();
|
||||
|
||||
assertThat(filter.mightContain(100)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBloomFilter_whenAddNStringsToItMoreThanDefinedExpectedInsertions_thenItWillReturnTrueForAlmostAllElements() {
|
||||
//when
|
||||
BloomFilter<Integer> filter = BloomFilter.create(
|
||||
Funnels.integerFunnel(),
|
||||
5,
|
||||
0.01);
|
||||
|
||||
//when
|
||||
IntStream.range(0, 100_000).forEach(filter::put);
|
||||
|
||||
|
||||
//then
|
||||
assertThat(filter.mightContain(1)).isTrue();
|
||||
assertThat(filter.mightContain(2)).isTrue();
|
||||
assertThat(filter.mightContain(3)).isTrue();
|
||||
assertThat(filter.mightContain(1_000_000)).isTrue();
|
||||
}
|
||||
}
|
||||
212
guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cache/GuavaCacheUnitTest.java
vendored
Normal file
212
guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cache/GuavaCacheUnitTest.java
vendored
Normal file
@@ -0,0 +1,212 @@
|
||||
package com.baeldung.guava.cache;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Optional;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.cache.RemovalCause;
|
||||
import com.google.common.cache.RemovalListener;
|
||||
import com.google.common.cache.RemovalNotification;
|
||||
import com.google.common.cache.Weigher;
|
||||
|
||||
public class GuavaCacheUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCacheMiss_thenAutoLoad() {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader);
|
||||
assertEquals(0, cache.size());
|
||||
assertEquals("HELLO", cache.getUnchecked("hello"));
|
||||
assertEquals(1, cache.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCacheReachMaxSize_thenEviction() {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).build(loader);
|
||||
cache.getUnchecked("first");
|
||||
cache.getUnchecked("second");
|
||||
cache.getUnchecked("third");
|
||||
cache.getUnchecked("forth");
|
||||
assertEquals(3, cache.size());
|
||||
assertNull(cache.getIfPresent("first"));
|
||||
assertEquals("FORTH", cache.getIfPresent("forth"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCacheReachMaxWeight_thenEviction() {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final Weigher<String, String> weighByLength = new Weigher<String, String>() {
|
||||
@Override
|
||||
public int weigh(final String key, final String value) {
|
||||
return value.length();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumWeight(16).weigher(weighByLength).build(loader);
|
||||
cache.getUnchecked("first");
|
||||
cache.getUnchecked("second");
|
||||
cache.getUnchecked("third");
|
||||
cache.getUnchecked("last");
|
||||
assertEquals(3, cache.size());
|
||||
assertNull(cache.getIfPresent("first"));
|
||||
assertEquals("LAST", cache.getIfPresent("last"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEntryIdle_thenEviction() throws InterruptedException {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterAccess(2, TimeUnit.MILLISECONDS).build(loader);
|
||||
cache.getUnchecked("hello");
|
||||
assertEquals(1, cache.size());
|
||||
cache.getUnchecked("hello");
|
||||
Thread.sleep(3);
|
||||
cache.getUnchecked("test");
|
||||
assertEquals(1, cache.size());
|
||||
assertNull(cache.getIfPresent("hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEntryLiveTimeExpire_thenEviction() throws InterruptedException {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MILLISECONDS).build(loader);
|
||||
cache.getUnchecked("hello");
|
||||
assertEquals(1, cache.size());
|
||||
Thread.sleep(3);
|
||||
cache.getUnchecked("test");
|
||||
assertEquals(1, cache.size());
|
||||
assertNull(cache.getIfPresent("hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWeekKeyHasNoRef_thenRemoveFromCache() {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().weakKeys().build(loader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSoftValue_thenRemoveFromCache() {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().softValues().build(loader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullValue_thenOptional() {
|
||||
final CacheLoader<String, Optional<String>> loader = new CacheLoader<String, Optional<String>>() {
|
||||
@Override
|
||||
public final Optional<String> load(final String key) {
|
||||
return Optional.fromNullable(getSuffix(key));
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, Optional<String>> cache = CacheBuilder.newBuilder().build(loader);
|
||||
assertEquals("txt", cache.getUnchecked("text.txt").get());
|
||||
assertFalse(cache.getUnchecked("hello").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLiveTimeEnd_thenRefresh() {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(loader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPreloadCache_thenUsePutAll() {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader);
|
||||
final Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("first", "FIRST");
|
||||
map.put("second", "SECOND");
|
||||
cache.putAll(map);
|
||||
assertEquals(2, cache.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEntryRemovedFromCache_thenNotify() {
|
||||
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public final String load(final String key) {
|
||||
return key.toUpperCase();
|
||||
}
|
||||
};
|
||||
final RemovalListener<String, String> listener = new RemovalListener<String, String>() {
|
||||
@Override
|
||||
public void onRemoval(final RemovalNotification<String, String> n) {
|
||||
if (n.wasEvicted()) {
|
||||
final String cause = n.getCause().name();
|
||||
assertEquals(RemovalCause.SIZE.toString(), cause);
|
||||
}
|
||||
}
|
||||
};
|
||||
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).removalListener(listener).build(loader);
|
||||
cache.getUnchecked("first");
|
||||
cache.getUnchecked("second");
|
||||
cache.getUnchecked("third");
|
||||
cache.getUnchecked("last");
|
||||
assertEquals(3, cache.size());
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
||||
private String getSuffix(final String str) {
|
||||
final int lastIndex = str.lastIndexOf('.');
|
||||
if (lastIndex == -1) {
|
||||
return null;
|
||||
}
|
||||
return str.substring(lastIndex + 1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.guava.cacheloader;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Iterables;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static com.google.common.collect.Iterables.cycle;
|
||||
import static com.google.common.collect.Maps.newHashMap;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class GuavaCacheLoaderUnitTest {
|
||||
int callCount = 0;
|
||||
|
||||
@Test
|
||||
public void givenAMap_whenAddingValues_thenCanTreatThemAsCache() {
|
||||
Map<String, String> cache = newHashMap();
|
||||
cache.put("foo", "cachedValueForFoo");
|
||||
cache.put("bar", "cachedValueForBar");
|
||||
|
||||
assertThat(cache.get("foo")).isEqualTo("cachedValueForFoo");
|
||||
assertThat(cache.get("bar")).isEqualTo("cachedValueForBar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCacheLoader_whenGettingItemTwice_shouldOnlyCallOnce() throws ExecutionException {
|
||||
|
||||
final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
|
||||
.build(new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public String load(final String s) throws Exception {
|
||||
return slowMethod(s);
|
||||
}
|
||||
});
|
||||
|
||||
String value = loadingCache.get("key");
|
||||
value = loadingCache.get("key");
|
||||
|
||||
assertThat(callCount).isEqualTo(1);
|
||||
assertThat(value).isEqualTo("key");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCacheLoader_whenRefreshingItem_shouldCallAgain() throws ExecutionException {
|
||||
|
||||
final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
|
||||
.build(new CacheLoader<String, String>() {
|
||||
@Override
|
||||
public String load(final String s) throws Exception {
|
||||
return slowMethod(s);
|
||||
}
|
||||
});
|
||||
|
||||
String value = loadingCache.get("key");
|
||||
loadingCache.refresh("key");
|
||||
|
||||
assertThat(callCount).isEqualTo(2);
|
||||
assertThat(value).isEqualTo("key");
|
||||
}
|
||||
|
||||
private String slowMethod(final String s) {
|
||||
callCount++;
|
||||
return s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.guava.eventbus;
|
||||
|
||||
import com.baeldung.guava.eventbus.CustomEvent;
|
||||
import com.baeldung.guava.eventbus.EventListener;
|
||||
import com.google.common.eventbus.EventBus;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class GuavaEventBusUnitTest {
|
||||
|
||||
private EventListener listener;
|
||||
private EventBus eventBus;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
eventBus = new EventBus();
|
||||
listener = new EventListener();
|
||||
|
||||
eventBus.register(listener);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
eventBus.unregister(listener);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringEvent_whenEventHandled_thenSuccess() {
|
||||
listener.resetEventsHandled();
|
||||
|
||||
eventBus.post("String Event");
|
||||
assertEquals(1, listener.getEventsHandled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomEvent_whenEventHandled_thenSuccess() {
|
||||
listener.resetEventsHandled();
|
||||
|
||||
CustomEvent customEvent = new CustomEvent("Custom Event");
|
||||
eventBus.post(customEvent);
|
||||
|
||||
assertEquals(1, listener.getEventsHandled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnSubscribedEvent_whenEventHandledByDeadEvent_thenSuccess() {
|
||||
listener.resetEventsHandled();
|
||||
|
||||
eventBus.post(12345);
|
||||
assertEquals(1, listener.getEventsHandled());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.baeldung.guava.mathutils;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.math.BigIntegerMath;
|
||||
|
||||
public class GuavaBigIntegerMathUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPerformBinomialOnTwoIntValues_shouldReturnResult() {
|
||||
BigInteger result = BigIntegerMath.binomial(6, 3);
|
||||
assertEquals(new BigInteger("20"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenProformCeilPowOfTwoBigIntegerValues_shouldReturnResult() {
|
||||
BigInteger result = BigIntegerMath.ceilingPowerOfTwo(new BigInteger("20"));
|
||||
assertEquals(new BigInteger("32"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideTwoBigIntegerValues_shouldDivideThemAndReturnTheResultForCeilingRounding() {
|
||||
BigInteger result = BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.CEILING);
|
||||
assertEquals(new BigInteger("4"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideTwoBigIntegerValues_shouldDivideThemAndReturnTheResultForFloorRounding() {
|
||||
BigInteger result = BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.FLOOR);
|
||||
assertEquals(new BigInteger("3"), result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDivideTwoBigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFactorailInteger_shouldFactorialThemAndReturnTheResultIfInIntRange() {
|
||||
BigInteger result = BigIntegerMath.factorial(5);
|
||||
assertEquals(new BigInteger("120"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFloorPowerOfInteger_shouldReturnValue() {
|
||||
BigInteger result = BigIntegerMath.floorPowerOfTwo(new BigInteger("30"));
|
||||
assertEquals(new BigInteger("16"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPowOfInteger_shouldReturnTrueIfPowerOfTwo() {
|
||||
boolean result = BigIntegerMath.isPowerOfTwo(new BigInteger("16"));
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog10BigIntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = BigIntegerMath.log10(new BigInteger("30"), RoundingMode.CEILING);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog10BigIntegerValues_shouldog10ThemAndReturnTheResultForFloorRounding() {
|
||||
int result = BigIntegerMath.log10(new BigInteger("30"), RoundingMode.FLOOR);
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenLog10BigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
BigIntegerMath.log10(new BigInteger("30"), RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog2BigIntegerValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = BigIntegerMath.log2(new BigInteger("30"), RoundingMode.CEILING);
|
||||
assertEquals(5, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog2BigIntegerValues_shouldog2ThemAndReturnTheResultForFloorRounding() {
|
||||
int result = BigIntegerMath.log2(new BigInteger("30"), RoundingMode.FLOOR);
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenLog2BigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
BigIntegerMath.log2(new BigInteger("30"), RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSqrtBigIntegerValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() {
|
||||
BigInteger result = BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.CEILING);
|
||||
assertEquals(new BigInteger("6"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSqrtBigIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() {
|
||||
BigInteger result = BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.FLOOR);
|
||||
assertEquals(new BigInteger("5"), result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenSqrtBigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.UNNECESSARY);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.baeldung.guava.mathutils;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.math.RoundingMode;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.math.DoubleMath;
|
||||
import com.google.common.math.IntMath;
|
||||
|
||||
public class GuavaDoubleMathUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFactorailDouble_shouldFactorialThemAndReturnTheResultIfInDoubleRange() {
|
||||
double result = DoubleMath.factorial(5);
|
||||
assertEquals(120, result, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFactorailDouble_shouldFactorialThemAndReturnDoubkeInfIfNotInDoubletRange() {
|
||||
double result = DoubleMath.factorial(Integer.MAX_VALUE);
|
||||
assertEquals(Double.POSITIVE_INFINITY, result, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFuzzyCompareDouble_shouldReturnZeroIfInRange() {
|
||||
int result = DoubleMath.fuzzyCompare(4, 4.05, 0.6);
|
||||
assertEquals(0, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFuzzyCompareDouble_shouldReturnNonZeroIfNotInRange() {
|
||||
int result = DoubleMath.fuzzyCompare(4, 5, 0.1);
|
||||
assertEquals(-1, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFuzzyEqualDouble_shouldReturnZeroIfInRange() {
|
||||
boolean result = DoubleMath.fuzzyEquals(4, 4.05, 0.6);
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFuzzyEqualDouble_shouldReturnNonZeroIfNotInRange() {
|
||||
boolean result = DoubleMath.fuzzyEquals(4, 5, 0.1);
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMathematicalIntDouble_shouldReturnTrueIfInRange() {
|
||||
boolean result = DoubleMath.isMathematicalInteger(5);
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMathematicalIntDouble_shouldReturnFalseIfNotInRange() {
|
||||
boolean result = DoubleMath.isMathematicalInteger(5.2);
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPowerOfTwoDouble_shouldReturnTrueIfIsPowerOfTwo() {
|
||||
boolean result = DoubleMath.isMathematicalInteger(4);
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPowerOfTwoDouble_shouldReturnFalseIsNotPowerOfTwoe() {
|
||||
boolean result = DoubleMath.isMathematicalInteger(5.2);
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog2Double_shouldReturnResult() {
|
||||
double result = DoubleMath.log2(4);
|
||||
assertEquals(2, result, 0);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenLog2DoubleValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = DoubleMath.log2(30, RoundingMode.CEILING);
|
||||
assertEquals(5, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog2DoubleValues_shouldog2ThemAndReturnTheResultForFloorRounding() {
|
||||
int result = DoubleMath.log2(30, RoundingMode.FLOOR);
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenLog2DoubleValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
DoubleMath.log2(30, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package com.baeldung.guava.mathutils;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.math.RoundingMode;
|
||||
|
||||
import com.google.common.math.IntMath;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GuavaIntMathUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPerformBinomialOnTwoIntegerValues_shouldReturnResultIfUnderInt() {
|
||||
int result = IntMath.binomial(6, 3);
|
||||
assertEquals(20, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPerformBinomialOnTwoIntegerValues_shouldReturnIntMaxIfUnderInt() {
|
||||
int result = IntMath.binomial(Integer.MAX_VALUE, 3);
|
||||
assertEquals(Integer.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenProformCeilPowOfTwoIntegerValues_shouldReturnResult() {
|
||||
int result = IntMath.ceilingPowerOfTwo(20);
|
||||
assertEquals(32, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckedAddTwoIntegerValues_shouldAddThemAndReturnTheSumIfNotOverflow() {
|
||||
int result = IntMath.checkedAdd(1, 2);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void gwhenCheckedAddTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() {
|
||||
IntMath.checkedAdd(Integer.MAX_VALUE, 100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnTheResultIfNotOverflow() {
|
||||
int result = IntMath.checkedMultiply(1, 2);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void gwhenCheckedMultiplyTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() {
|
||||
IntMath.checkedMultiply(Integer.MAX_VALUE, 100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckedPowTwoIntegerValues_shouldPowThemAndReturnTheResultIfNotOverflow() {
|
||||
int result = IntMath.checkedPow(2, 3);
|
||||
assertEquals(8, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void gwhenCheckedPowTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() {
|
||||
IntMath.checkedPow(Integer.MAX_VALUE, 100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckedSubstractTwoIntegerValues_shouldSubstractThemAndReturnTheResultIfNotOverflow() {
|
||||
int result = IntMath.checkedSubtract(4, 1);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void gwhenCheckedSubstractTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() {
|
||||
IntMath.checkedSubtract(Integer.MAX_VALUE, -100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideTwoIntegerValues_shouldDivideThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = IntMath.divide(10, 3, RoundingMode.CEILING);
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideTwoIntegerValues_shouldDivideThemAndReturnTheResultForFloorRounding() {
|
||||
int result = IntMath.divide(10, 3, RoundingMode.FLOOR);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDivideTwoIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
IntMath.divide(10, 3, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFactorailInteger_shouldFactorialThemAndReturnTheResultIfInIntRange() {
|
||||
int result = IntMath.factorial(5);
|
||||
assertEquals(120, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFactorailInteger_shouldFactorialThemAndReturnIntMaxIfNotInIntRange() {
|
||||
int result = IntMath.factorial(Integer.MAX_VALUE);
|
||||
assertEquals(Integer.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFloorPowerOfInteger_shouldReturnValue() {
|
||||
int result = IntMath.floorPowerOfTwo(30);
|
||||
assertEquals(16, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGcdOfTwoIntegers_shouldReturnValue() {
|
||||
int result = IntMath.gcd(30, 40);
|
||||
assertEquals(10, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPowOfInteger_shouldReturnTrueIfPowerOfTwo() {
|
||||
boolean result = IntMath.isPowerOfTwo(16);
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPowOfInteger_shouldReturnFalseeIfNotPowerOfTwo() {
|
||||
boolean result = IntMath.isPowerOfTwo(20);
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPrineOfInteger_shouldReturnFalseeIfNotPrime() {
|
||||
boolean result = IntMath.isPrime(20);
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog10IntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = IntMath.log10(30, RoundingMode.CEILING);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog10IntegerValues_shouldog10ThemAndReturnTheResultForFloorRounding() {
|
||||
int result = IntMath.log10(30, RoundingMode.FLOOR);
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenLog10IntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
IntMath.log10(30, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog2IntegerValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = IntMath.log2(30, RoundingMode.CEILING);
|
||||
assertEquals(5, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog2IntegerValues_shouldog2ThemAndReturnTheResultForFloorRounding() {
|
||||
int result = IntMath.log2(30, RoundingMode.FLOOR);
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenLog2IntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
IntMath.log2(30, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMeanTwoIntegerValues_shouldMeanThemAndReturnTheResult() {
|
||||
int result = IntMath.mean(30, 20);
|
||||
assertEquals(25, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModTwoIntegerValues_shouldModThemAndReturnTheResult() {
|
||||
int result = IntMath.mod(30, 4);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPowTwoIntegerValues_shouldPowThemAndReturnTheResult() {
|
||||
int result = IntMath.pow(6, 4);
|
||||
assertEquals(1296, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnTheResult() {
|
||||
int result = IntMath.saturatedAdd(6, 4);
|
||||
assertEquals(10, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnIntMaxIfOverflow() {
|
||||
int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 1000);
|
||||
assertEquals(Integer.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnIntMinIfUnderflow() {
|
||||
int result = IntMath.saturatedAdd(Integer.MIN_VALUE, -1000);
|
||||
assertEquals(Integer.MIN_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnTheResult() {
|
||||
int result = IntMath.saturatedMultiply(6, 4);
|
||||
assertEquals(24, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() {
|
||||
int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 1000);
|
||||
assertEquals(Integer.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMinIfUnderflow() {
|
||||
int result = IntMath.saturatedMultiply(Integer.MIN_VALUE, 1000);
|
||||
assertEquals(Integer.MIN_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnTheResult() {
|
||||
int result = IntMath.saturatedPow(6, 2);
|
||||
assertEquals(36, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnIntMaxIfOverflow() {
|
||||
int result = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
|
||||
assertEquals(Integer.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnIntMinIfUnderflow() {
|
||||
int result = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
|
||||
assertEquals(Integer.MIN_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractThemAndReturnTheResult() {
|
||||
int result = IntMath.saturatedSubtract(6, 2);
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractwThemAndReturnIntMaxIfOverflow() {
|
||||
int result = IntMath.saturatedSubtract(Integer.MAX_VALUE, -2);
|
||||
assertEquals(Integer.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractThemAndReturnIntMinIfUnderflow() {
|
||||
int result = IntMath.saturatedSubtract(Integer.MIN_VALUE, 3);
|
||||
assertEquals(Integer.MIN_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = IntMath.sqrt(30, RoundingMode.CEILING);
|
||||
assertEquals(6, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() {
|
||||
int result = IntMath.sqrt(30, RoundingMode.FLOOR);
|
||||
assertEquals(5, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenSqrtIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
IntMath.sqrt(30, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package com.baeldung.guava.mathutils;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.math.RoundingMode;
|
||||
|
||||
import com.google.common.math.LongMath;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GuavaLongMathUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPerformBinomialOnTwoLongValues_shouldReturnResultIfUnderLong() {
|
||||
long result = LongMath.binomial(6, 3);
|
||||
assertEquals(20L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenProformCeilPowOfTwoLongValues_shouldReturnResult() {
|
||||
long result = LongMath.ceilingPowerOfTwo(20L);
|
||||
assertEquals(32L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckedAddTwoLongValues_shouldAddThemAndReturnTheSumIfNotOverflow() {
|
||||
long result = LongMath.checkedAdd(1L, 2L);
|
||||
assertEquals(3L, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenCheckedAddTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
|
||||
LongMath.checkedAdd(Long.MAX_VALUE, 100L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckedMultiplyTwoLongValues_shouldMultiplyThemAndReturnTheResultIfNotOverflow() {
|
||||
long result = LongMath.checkedMultiply(3L, 2L);
|
||||
assertEquals(6L, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenCheckedMultiplyTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
|
||||
LongMath.checkedMultiply(Long.MAX_VALUE, 100L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckedPowTwoLongValues_shouldPowThemAndReturnTheResultIfNotOverflow() {
|
||||
long result = LongMath.checkedPow(2L, 3);
|
||||
assertEquals(8L, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void gwhenCheckedPowTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
|
||||
LongMath.checkedPow(Long.MAX_VALUE, 100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckedSubstractTwoLongValues_shouldSubstractThemAndReturnTheResultIfNotOverflow() {
|
||||
long result = LongMath.checkedSubtract(4L, 1L);
|
||||
assertEquals(3L, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void gwhenCheckedSubstractTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
|
||||
LongMath.checkedSubtract(Long.MAX_VALUE, -100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideTwoLongValues_shouldDivideThemAndReturnTheResultForCeilingRounding() {
|
||||
long result = LongMath.divide(10L, 3L, RoundingMode.CEILING);
|
||||
assertEquals(4L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivideTwoLongValues_shouldDivideThemAndReturnTheResultForFloorRounding() {
|
||||
long result = LongMath.divide(10L, 3L, RoundingMode.FLOOR);
|
||||
assertEquals(3L, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDivideTwoLongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
LongMath.divide(10L, 3L, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFactorailLong_shouldFactorialThemAndReturnTheResultIfInIntRange() {
|
||||
long result = LongMath.factorial(5);
|
||||
assertEquals(120L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFactorailLong_shouldFactorialThemAndReturnIntMaxIfNotInIntRange() {
|
||||
long result = LongMath.factorial(Integer.MAX_VALUE);
|
||||
assertEquals(Long.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFloorPowerOfLong_shouldReturnValue() {
|
||||
long result = LongMath.floorPowerOfTwo(30L);
|
||||
assertEquals(16L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGcdOfTwoLongs_shouldReturnValue() {
|
||||
long result = LongMath.gcd(30L, 40L);
|
||||
assertEquals(10L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPowOfLong_shouldReturnTrueIfPowerOfTwo() {
|
||||
boolean result = LongMath.isPowerOfTwo(16L);
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPowOfLong_shouldReturnFalseeIfNotPowerOfTwo() {
|
||||
boolean result = LongMath.isPowerOfTwo(20L);
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsPrineOfLong_shouldReturnFalseeIfNotPrime() {
|
||||
boolean result = LongMath.isPrime(20L);
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog10LongValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = LongMath.log10(30L, RoundingMode.CEILING);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog10LongValues_shouldog10ThemAndReturnTheResultForFloorRounding() {
|
||||
int result = LongMath.log10(30L, RoundingMode.FLOOR);
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenLog10LongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
LongMath.log10(30L, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog2LongValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() {
|
||||
int result = LongMath.log2(30L, RoundingMode.CEILING);
|
||||
assertEquals(5, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLog2LongValues_shouldog2ThemAndReturnTheResultForFloorRounding() {
|
||||
int result = LongMath.log2(30L, RoundingMode.FLOOR);
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenLog2LongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
LongMath.log2(30L, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMeanTwoLongValues_shouldMeanThemAndReturnTheResult() {
|
||||
long result = LongMath.mean(30L, 20L);
|
||||
assertEquals(25L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModLongAndIntegerValues_shouldModThemAndReturnTheResult() {
|
||||
int result = LongMath.mod(30L, 4);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModTwoLongValues_shouldModThemAndReturnTheResult() {
|
||||
long result = LongMath.mod(30L, 4L);
|
||||
assertEquals(2L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPowTwoLongValues_shouldPowThemAndReturnTheResult() {
|
||||
long result = LongMath.pow(6L, 4);
|
||||
assertEquals(1296L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnTheResult() {
|
||||
long result = LongMath.saturatedAdd(6L, 4L);
|
||||
assertEquals(10L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnIntMaxIfOverflow() {
|
||||
long result = LongMath.saturatedAdd(Long.MAX_VALUE, 1000L);
|
||||
assertEquals(Long.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnIntMinIfUnderflow() {
|
||||
long result = LongMath.saturatedAdd(Long.MIN_VALUE, -1000);
|
||||
assertEquals(Long.MIN_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnTheResult() {
|
||||
long result = LongMath.saturatedMultiply(6L, 4L);
|
||||
assertEquals(24L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() {
|
||||
long result = LongMath.saturatedMultiply(Long.MAX_VALUE, 1000L);
|
||||
assertEquals(Long.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnTheResult() {
|
||||
long result = LongMath.saturatedPow(6L, 2);
|
||||
assertEquals(36L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnIntMaxIfOverflow() {
|
||||
long result = LongMath.saturatedPow(Long.MAX_VALUE, 2);
|
||||
assertEquals(Long.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnIntMinIfUnderflow() {
|
||||
long result = LongMath.saturatedPow(Long.MIN_VALUE, 3);
|
||||
assertEquals(Long.MIN_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedSubstractTwoLongValues_shouldSubstractThemAndReturnTheResult() {
|
||||
long result = LongMath.saturatedSubtract(6L, 2L);
|
||||
assertEquals(4L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedSubstractTwoLongValues_shouldSubstractwThemAndReturnIntMaxIfOverflow() {
|
||||
long result = LongMath.saturatedSubtract(Long.MAX_VALUE, -2L);
|
||||
assertEquals(Long.MAX_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaturatedSubstractTwoLongValues_shouldSubstractThemAndReturnIntMinIfUnderflow() {
|
||||
long result = LongMath.saturatedSubtract(Long.MIN_VALUE, 3L);
|
||||
assertEquals(Long.MIN_VALUE, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() {
|
||||
long result = LongMath.sqrt(30L, RoundingMode.CEILING);
|
||||
assertEquals(6L, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForFloorRounding() {
|
||||
long result = LongMath.sqrt(30L, RoundingMode.FLOOR);
|
||||
assertEquals(5L, result);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenSqrtLongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() {
|
||||
LongMath.sqrt(30L, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package com.baeldung.guava.mathutils;
|
||||
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.math.DoubleMath;
|
||||
import com.google.common.math.IntMath;
|
||||
|
||||
public class GuavaMathUnitTest {
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenSumOverflow_thenThrowException() {
|
||||
IntMath.checkedAdd(Integer.MAX_VALUE, 1);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenSumUnderflow_thenThrowException() {
|
||||
IntMath.checkedAdd(Integer.MIN_VALUE, -1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_sum() {
|
||||
int result = IntMath.checkedAdd(2, 1);
|
||||
assertThat(result, equalTo(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumOverflow_thenReturnMaxInteger() {
|
||||
int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 100);
|
||||
assertThat(result, equalTo(Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumUnderflow_thenReturnMinInteger() {
|
||||
int result = IntMath.saturatedAdd(Integer.MIN_VALUE, -100);
|
||||
assertThat(result, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDifferenceOverflow_thenThrowException() {
|
||||
IntMath.checkedSubtract(Integer.MAX_VALUE, -1);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDifferenceUnderflow_thenThrowException() {
|
||||
IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_difference() {
|
||||
int result = IntMath.checkedSubtract(200, 100);
|
||||
assertThat(result, equalTo(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDifferenceOverflow_thenReturnMaxInteger() {
|
||||
int result = IntMath.saturatedSubtract(Integer.MAX_VALUE, -1);
|
||||
assertThat(result, equalTo(Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDifferenceUnderflow_thenReturnMinInteger() {
|
||||
int result = IntMath.saturatedSubtract(Integer.MIN_VALUE, 1);
|
||||
assertThat(result, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenProductOverflow_thenThrowException() {
|
||||
IntMath.checkedMultiply(Integer.MAX_VALUE, 2);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenProductUnderflow_thenThrowException() {
|
||||
IntMath.checkedMultiply(Integer.MIN_VALUE, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_product() {
|
||||
int result = IntMath.checkedMultiply(21, 3);
|
||||
assertThat(result, equalTo(63));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenProductOverflow_thenReturnMaxInteger() {
|
||||
int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 2);
|
||||
assertThat(result, equalTo(Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenProductUnderflow_thenReturnMinInteger() {
|
||||
int result = IntMath.saturatedMultiply(Integer.MIN_VALUE, 2);
|
||||
assertThat(result, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenPowerOverflow_thenThrowException() {
|
||||
IntMath.checkedPow(Integer.MAX_VALUE, 2);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenPowerUnderflow_thenThrowException() {
|
||||
IntMath.checkedPow(Integer.MIN_VALUE, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_power() {
|
||||
int result = IntMath.saturatedPow(3, 3);
|
||||
assertThat(result, equalTo(27));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPowerOverflow_thenReturnMaxInteger() {
|
||||
int result = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
|
||||
assertThat(result, equalTo(Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPowerUnderflow_thenReturnMinInteger() {
|
||||
int result = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
|
||||
assertThat(result, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_round_divide_result() {
|
||||
int result1 = IntMath.divide(3, 2, RoundingMode.DOWN);
|
||||
assertThat(result1, equalTo(1));
|
||||
|
||||
int result2 = IntMath.divide(3, 2, RoundingMode.UP);
|
||||
assertThat(result2, equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_round_log2_result() {
|
||||
int result1 = IntMath.log2(5, RoundingMode.FLOOR);
|
||||
assertThat(result1, equalTo(2));
|
||||
|
||||
int result2 = IntMath.log2(5, RoundingMode.CEILING);
|
||||
assertThat(result2, equalTo(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_round_log10_result() {
|
||||
int result = IntMath.log10(11, RoundingMode.HALF_UP);
|
||||
assertThat(result, equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_round_sqrt_result() {
|
||||
int result = IntMath.sqrt(4, RoundingMode.UNNECESSARY);
|
||||
assertThat(result, equalTo(2));
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenNeedRounding_thenThrowException() {
|
||||
IntMath.sqrt(5, RoundingMode.UNNECESSARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_gcd() {
|
||||
int result = IntMath.gcd(15, 20);
|
||||
assertThat(result, equalTo(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_mod() {
|
||||
int result = IntMath.mod(8, 3);
|
||||
assertThat(result, equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_test_if_is_power_of_two() {
|
||||
boolean result1 = IntMath.isPowerOfTwo(8);
|
||||
assertTrue(result1);
|
||||
|
||||
boolean result2 = IntMath.isPowerOfTwo(9);
|
||||
assertFalse(result2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_factorial() {
|
||||
int result = IntMath.factorial(4);
|
||||
assertThat(result, equalTo(24));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_binomial() {
|
||||
int result = IntMath.binomial(7, 3);
|
||||
assertThat(result, equalTo(35));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_detect_integer() {
|
||||
boolean result1 = DoubleMath.isMathematicalInteger(2.0);
|
||||
assertThat(result1, equalTo(true));
|
||||
boolean result2 = DoubleMath.isMathematicalInteger(2.1);
|
||||
assertThat(result2, equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_round_to_integer_types() {
|
||||
int result3 = DoubleMath.roundToInt(2.5, RoundingMode.DOWN);
|
||||
assertThat(result3, equalTo(2));
|
||||
|
||||
long result4 = DoubleMath.roundToLong(2.5, RoundingMode.HALF_UP);
|
||||
assertThat(result4, equalTo(3L));
|
||||
|
||||
BigInteger result5 = DoubleMath.roundToBigInteger(2.5, RoundingMode.UP);
|
||||
assertThat(result5, equalTo(new BigInteger("3")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_log_2() {
|
||||
int result6 = DoubleMath.log2(10, RoundingMode.UP);
|
||||
assertThat(result6, equalTo(4));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.guava.ratelimiter;
|
||||
|
||||
|
||||
import com.google.common.util.concurrent.RateLimiter;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class RateLimiterLongRunningUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLimitedResource_whenUseRateLimiter_thenShouldLimitPermits() {
|
||||
//given
|
||||
RateLimiter rateLimiter = RateLimiter.create(100);
|
||||
|
||||
//when
|
||||
long startTime = ZonedDateTime.now().getSecond();
|
||||
IntStream.range(0, 1000).forEach(i -> {
|
||||
rateLimiter.acquire();
|
||||
doSomeLimitedOperation();
|
||||
});
|
||||
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
|
||||
|
||||
//then
|
||||
assertThat(elapsedTimeSeconds >= 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLimitedResource_whenRequestTwice_thenShouldPermitWithoutBlocking() {
|
||||
//given
|
||||
RateLimiter rateLimiter = RateLimiter.create(2);
|
||||
|
||||
//when
|
||||
long startTime = ZonedDateTime.now().getSecond();
|
||||
rateLimiter.acquire(1);
|
||||
doSomeLimitedOperation();
|
||||
rateLimiter.acquire(1);
|
||||
doSomeLimitedOperation();
|
||||
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
|
||||
|
||||
//then
|
||||
assertThat(elapsedTimeSeconds <= 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLimitedResource_whenRequestOnce_thenShouldPermitWithoutBlocking() {
|
||||
//given
|
||||
RateLimiter rateLimiter = RateLimiter.create(100);
|
||||
|
||||
//when
|
||||
long startTime = ZonedDateTime.now().getSecond();
|
||||
rateLimiter.acquire(100);
|
||||
doSomeLimitedOperation();
|
||||
long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime;
|
||||
|
||||
//then
|
||||
assertThat(elapsedTimeSeconds <= 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLimitedResource_whenTryAcquire_shouldNotBlockIndefinitely() {
|
||||
//given
|
||||
RateLimiter rateLimiter = RateLimiter.create(1);
|
||||
|
||||
//when
|
||||
rateLimiter.acquire();
|
||||
boolean result = rateLimiter.tryAcquire(2, 10, TimeUnit.MILLISECONDS);
|
||||
|
||||
//then
|
||||
assertThat(result).isFalse();
|
||||
|
||||
}
|
||||
|
||||
private void doSomeLimitedOperation() {
|
||||
//some computing
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.baeldung.guava.reflectionutils;
|
||||
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.reflect.Invokable;
|
||||
import com.google.common.reflect.TypeToken;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class GuavaReflectionUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoGenericList_whenCheckIsAssignableFrom_thenReturnTrueDueToTypeErasure() {
|
||||
//given
|
||||
ArrayList<String> stringList = Lists.newArrayList();
|
||||
ArrayList<Integer> intList = Lists.newArrayList();
|
||||
|
||||
//when
|
||||
boolean result = stringList.getClass().isAssignableFrom(intList.getClass());
|
||||
|
||||
//then
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTypeToken_whenResolveType_thenShouldResolveProperType() {
|
||||
//given
|
||||
TypeToken<List<String>> stringListToken = new TypeToken<List<String>>() {
|
||||
};
|
||||
TypeToken<List<Integer>> integerListToken = new TypeToken<List<Integer>>() {
|
||||
};
|
||||
TypeToken<List<? extends Number>> numberTypeToken = new TypeToken<List<? extends Number>>() {
|
||||
};
|
||||
|
||||
//then
|
||||
assertFalse(stringListToken.isSubtypeOf(integerListToken));
|
||||
assertFalse(numberTypeToken.isSubtypeOf(integerListToken));
|
||||
assertTrue(integerListToken.isSubtypeOf(numberTypeToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomClass_whenCaptureGeneric_thenReturnTypeAtRuntime() {
|
||||
//given
|
||||
ParametrizedClass<String> parametrizedClass = new ParametrizedClass<String>() {
|
||||
};
|
||||
|
||||
//then
|
||||
assertEquals(parametrizedClass.type, TypeToken.of(String.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenComplexType_whenGetTypeArgument_thenShouldReturnTypeAtRuntime() {
|
||||
//given
|
||||
TypeToken<Function<Integer, String>> funToken = new TypeToken<Function<Integer, String>>() {
|
||||
};
|
||||
|
||||
//when
|
||||
TypeToken<?> funResultToken = funToken.resolveType(Function.class.getTypeParameters()[1]);
|
||||
|
||||
//then
|
||||
assertEquals(funResultToken, TypeToken.of(String.class));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenMapType_whenGetTypeArgumentOfEntry_thenShouldReturnTypeAtRuntime() throws NoSuchMethodException {
|
||||
//given
|
||||
TypeToken<Map<String, Integer>> mapToken = new TypeToken<Map<String, Integer>>() {
|
||||
};
|
||||
|
||||
//when
|
||||
TypeToken<?> entrySetToken = mapToken.resolveType(Map.class.getMethod("entrySet").getGenericReturnType());
|
||||
|
||||
//then
|
||||
assertEquals(entrySetToken, new TypeToken<Set<Map.Entry<String, Integer>>>() {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvokable_whenCheckPublicMethod_shouldReturnTrue() throws NoSuchMethodException {
|
||||
//given
|
||||
Method method = CustomClass.class.getMethod("somePublicMethod");
|
||||
Invokable<CustomClass, ?> invokable = new TypeToken<CustomClass>() {
|
||||
}.method(method);
|
||||
|
||||
//when
|
||||
boolean isPublicStandradJava = Modifier.isPublic(method.getModifiers());
|
||||
boolean isPublicGuava = invokable.isPublic();
|
||||
//then
|
||||
assertTrue(isPublicStandradJava);
|
||||
assertTrue(isPublicGuava);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvokable_whenCheckFinalMethod_shouldReturnFalseForIsOverridable() throws NoSuchMethodException {
|
||||
//given
|
||||
Method method = CustomClass.class.getMethod("notOverridablePublicMethod");
|
||||
Invokable<CustomClass, ?> invokable = new TypeToken<CustomClass>() {
|
||||
}.method(method);
|
||||
|
||||
//when
|
||||
boolean isOverridableStandardJava = (!(Modifier.isFinal(method.getModifiers()) || Modifier.isPrivate(method.getModifiers())
|
||||
|| Modifier.isStatic(method.getModifiers())
|
||||
|| Modifier.isFinal(method.getDeclaringClass().getModifiers())));
|
||||
boolean isOverridableFinalGauava = invokable.isOverridable();
|
||||
|
||||
//then
|
||||
assertFalse(isOverridableStandardJava);
|
||||
assertFalse(isOverridableFinalGauava);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfType_whenGetReturnRype_shouldCaptureTypeAtRuntime() throws NoSuchMethodException {
|
||||
//given
|
||||
Method getMethod = List.class.getMethod("get", int.class);
|
||||
|
||||
//when
|
||||
Invokable<List<Integer>, ?> invokable = new TypeToken<List<Integer>>() {
|
||||
}.method(getMethod);
|
||||
|
||||
//then
|
||||
assertEquals(TypeToken.of(Integer.class), invokable.getReturnType()); // Not Object.class!
|
||||
}
|
||||
|
||||
|
||||
abstract class ParametrizedClass<T> {
|
||||
TypeToken<T> type = new TypeToken<T>(getClass()) {
|
||||
};
|
||||
}
|
||||
|
||||
class CustomClass {
|
||||
public void somePublicMethod() {
|
||||
}
|
||||
|
||||
public final void notOverridablePublicMethod() {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
13
guava-modules/guava-utilities/src/test/resources/.gitignore
vendored
Normal file
13
guava-modules/guava-utilities/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -0,0 +1 @@
|
||||
John Jane Adam Tom
|
||||
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
@@ -0,0 +1 @@
|
||||
Test
|
||||
@@ -0,0 +1,4 @@
|
||||
John
|
||||
Jane
|
||||
Adam
|
||||
Tom
|
||||
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
BIN
guava-modules/guava-utilities/src/test/resources/test_le.txt
Normal file
BIN
guava-modules/guava-utilities/src/test/resources/test_le.txt
Normal file
Binary file not shown.
@@ -17,9 +17,16 @@
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>guava-utilities</module>
|
||||
<module>guava-core</module>
|
||||
<module>guava-18</module>
|
||||
<module>guava-19</module>
|
||||
<module>guava-21</module>
|
||||
<module>guava-collections</module>
|
||||
<module>guava-collections-list</module>
|
||||
<module>guava-collections-map</module>
|
||||
<module>guava-collections-set</module>
|
||||
<module>guava-io</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
|
||||
Reference in New Issue
Block a user