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>
|
||||
@@ -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)
|
||||
@@ -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>
|
||||
+82
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
+56
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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>
|
||||
+20
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -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;
|
||||
}
|
||||
}
|
||||
+20
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -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 {
|
||||
}
|
||||
+30
@@ -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"));
|
||||
}
|
||||
}
|
||||
+53
@@ -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);
|
||||
}
|
||||
}
|
||||
+105
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -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());
|
||||
}
|
||||
}
|
||||
+132
@@ -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();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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,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)
|
||||
@@ -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>
|
||||
+96
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -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);
|
||||
}
|
||||
}
|
||||
+92
@@ -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();
|
||||
}
|
||||
}
|
||||
+125
@@ -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();
|
||||
}
|
||||
}
|
||||
+131
@@ -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));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user