[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

View File

@@ -0,0 +1,31 @@
=========
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [Java Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
- [Sorting in Java](http://www.baeldung.com/java-sorting)
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)
- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint)

View File

@@ -0,0 +1,78 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<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.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>${commons-exec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
<commons-exec.version>1.3</commons-exec.version>
</properties>
</project>

View File

@@ -0,0 +1,37 @@
package com.baeldung.charstack;
import java.util.Iterator;
import java.util.LinkedList;
public class CharStack {
private LinkedList<Character> items;
public CharStack() {
this.items = new LinkedList<Character>();
}
public void push(Character item) {
items.push(item);
}
public Character peek() {
return items.getFirst();
}
public Character pop() {
Iterator<Character> iter = items.iterator();
Character item = iter.next();
if (item != null) {
iter.remove();
return item;
}
return null;
}
public int size() {
return items.size();
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.charstack;
public class CharStackWithArray {
private char[] elements;
private int size;
public CharStackWithArray() {
size = 0;
elements = new char[4];
}
public int size() {
return size;
}
public char peek() {
if (size == 0) {
throw new EmptyStackException();
}
return elements[size - 1];
}
public char pop() {
if (size == 0) {
throw new EmptyStackException();
}
return elements[--size];
}
public void push(char item) {
ensureCapacity(size + 1);
elements[size] = item;
size++;
}
private void ensureCapacity(int newSize) {
char newBiggerArray[];
if (elements.length < newSize) {
newBiggerArray = new char[elements.length * 2];
System.arraycopy(elements, 0, newBiggerArray, 0, size);
elements = newBiggerArray;
}
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.charstack;
public class EmptyStackException extends RuntimeException {
public EmptyStackException() {
super("Stack is empty");
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.combiningcollections;
import java.util.Arrays;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
import com.google.common.collect.ObjectArrays;
public class CombiningArrays {
public static Object[] usingNativeJava(Object[] first, Object[] second) {
Object[] combined = new Object[first.length + second.length];
System.arraycopy(first, 0, combined, 0, first.length);
System.arraycopy(second, 0, combined, first.length, second.length);
return combined;
}
public static Object[] usingJava8ObjectStream(Object[] first, Object[] second) {
Object[] combined = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray();
return combined;
}
public static Object[] usingJava8FlatMaps(Object[] first, Object[] second) {
Object[] combined = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new);
return combined;
}
public static Object[] usingApacheCommons(Object[] first, Object[] second) {
Object[] combined = ArrayUtils.addAll(first, second);
return combined;
}
public static Object[] usingGuava(Object[] first, Object[] second) {
Object [] combined = ObjectArrays.concat(first, second, Object.class);
return combined;
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.combiningcollections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.collections4.ListUtils;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class CombiningLists {
public static List<Object> usingNativeJava(List<Object> first, List<Object> second) {
List<Object> combined = new ArrayList<>();
combined.addAll(first);
combined.addAll(second);
return combined;
}
public static List<Object> usingJava8ObjectStream(List<Object> first, List<Object> second) {
List<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList());
return combined;
}
public static List<Object> usingJava8FlatMaps(List<Object> first, List<Object> second) {
List<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList());
return combined;
}
public static List<Object> usingApacheCommons(List<Object> first, List<Object> second) {
List<Object> combined = ListUtils.union(first, second);
return combined;
}
public static List<Object> usingGuava(List<Object> first, List<Object> second) {
Iterable<Object> combinedIterables = Iterables.unmodifiableIterable(
Iterables.concat(first, second));
List<Object> combined = Lists.newArrayList(combinedIterables);
return combined;
}
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.combiningcollections;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.exec.util.MapUtils;
import com.google.common.collect.ImmutableMap;
public class CombiningMaps {
public static Map<String, String> usingPlainJava(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = new HashMap<>();
combined.putAll(first);
combined.putAll(second);
return combined;
}
public static Map<String, String> usingJava8ForEach(Map<String, String> first, Map<String, String> second) {
second.forEach((key, value) -> first.merge(key, value, String::concat));
return first;
}
public static Map<String, String> usingJava8FlatMaps(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = Stream.of(first, second).map(Map::entrySet).flatMap(Collection::stream)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, String::concat));
return combined;
}
public static Map<String, String> usingApacheCommons(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = MapUtils.merge(first, second);
return combined;
}
public static Map<String, String> usingGuava(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = ImmutableMap.<String, String>builder()
.putAll(first)
.putAll(second)
.build();
return combined;
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.combiningcollections;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.collections4.SetUtils;
import com.google.common.collect.Sets;
public class CombiningSets {
public static Set<Object> usingNativeJava(Set<Object> first, Set<Object> second) {
Set<Object> combined = new HashSet<>();
combined.addAll(first);
combined.addAll(second);
return combined;
}
public static Set<Object> usingJava8ObjectStream(Set<Object> first, Set<Object> second) {
Set<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet());
return combined;
}
public static Set<Object> usingJava8FlatMaps(Set<Object> first, Set<Object> second) {
Set<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet());
return combined;
}
public static Set<Object> usingApacheCommons(Set<Object> first, Set<Object> second) {
Set<Object> combined = SetUtils.union(first, second);
return combined;
}
public static Set<Object> usingGuava(Set<Object> first, Set<Object> second) {
Set<Object> combined = Sets.union(first, second);
return combined;
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.hashtable;
public class Word {
private String name;
public Word(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Word))
return false;
Word word = (Word) o;
return word.getName().equals(this.name) ? true : false;
}
public int hashCode() {
return name.hashCode();
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.iteratorguide;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IteratorGuide {
public static void main(String[] args) {
List<String> items = new ArrayList<>();
items.add("ONE");
items.add("TWO");
items.add("THREE");
Iterator<String> iter = items.iterator();
while (iter.hasNext()) {
String next = iter.next();
System.out.println(next);
iter.remove();
}
ListIterator<String> listIterator = items.listIterator();
while(listIterator.hasNext()) {
String nextWithIndex = items.get(listIterator.nextIndex());
String next = listIterator.next();
if( "ONE".equals(next)) {
listIterator.set("SWAPPED");
}
}
listIterator.add("FOUR");
while(listIterator.hasPrevious()) {
String previousWithIndex = items.get(listIterator.previousIndex());
String previous = listIterator.previous();
System.out.println(previous);
}
listIterator.forEachRemaining(e -> {
System.out.println(e);
});
}
}

View File

@@ -0,0 +1,80 @@
package com.baeldung.iterators;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
/**
* Source code https://github.com/eugenp/tutorials
*
* @author Santosh Thakur
*/
public class Iterators {
public static int failFast1() {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
Integer number = iterator.next();
numbers.add(50);
}
return numbers.size();
}
public static int failFast2() {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
if (iterator.next() == 30) {
// will not throw Exception
iterator.remove();
}
}
System.out.println("using iterator's remove method = " + numbers);
iterator = numbers.iterator();
while (iterator.hasNext()) {
if (iterator.next() == 40) {
// will throw Exception on
// next call of next() method
numbers.remove(2);
}
}
return numbers.size();
}
public static int failSafe1() {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("First", 10);
map.put("Second", 20);
map.put("Third", 30);
map.put("Fourth", 40);
Iterator<String> iterator = map.keySet()
.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
map.put("Fifth", 50);
}
return map.size();
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
public class CollectionUtilsCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> apacheEventNumberPredicate = item -> item % 2 == 0;
CollectionUtils.filter(baseCollection, apacheEventNumberPredicate);
return baseCollection;
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import org.eclipse.collections.api.block.predicate.Predicate;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.utility.Iterate;
public class EclipseCollectionsCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> eclipsePredicate = item -> item % 2 == 0;
Collection<Integer> filteredList = Lists.mutable.ofAll(baseCollection)
.select(eclipsePredicate);
return filteredList;
}
static public Collection<Integer> findEvenNumbersUsingIterate(Collection<Integer> baseCollection) {
Predicate<Integer> eclipsePredicate = new Predicate<Integer>() {
private static final long serialVersionUID = 1L;
@Override
public boolean accept(Integer arg0) {
return arg0 % 2 == 0;
}
};
Collection<Integer> filteredList = Iterate.select(baseCollection, eclipsePredicate);
return filteredList;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
public class GuavaCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> guavaPredicate = item -> item % 2 == 0;
Collection<Integer> filteredCollection = Collections2.filter(baseCollection, guavaPredicate);
return filteredCollection;
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class StreamsCollectionFilter {
public static <T> Collection<T> filterCollectionHelperMethod(Collection<T> baseCollection, Predicate<T> predicate) {
return baseCollection.stream()
.filter(predicate)
.collect(Collectors.toList());
}
static public Collection<Integer> findEvenNumbersUsingHelperMethod(Collection<Integer> baseCollection) {
return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0);
}
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> streamsPredicate = item -> item % 2 == 0;
return baseCollection.stream()
.filter(streamsPredicate)
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,65 @@
package com.baeldung.java.iterable;
import java.util.Collection;
import java.util.stream.StreamSupport;
import org.apache.commons.collections4.IterableUtils;
import com.google.common.collect.Iterables;
/**
* Provides methods for getting the size of an {@link Iterable} object.
*/
public class IterableSize {
/**
* Get the size of {@code Iterable} using Java 7.
*
* @param data the iterable
* @return the size of the iterable
*/
public static int sizeUsingJava7(final Iterable data) {
if (data instanceof Collection) {
return ((Collection<?>) data).size();
}
int counter = 0;
for (final Object i : data) {
counter++;
}
return counter;
}
/**
* Get the size of {@code Iterable} using Java 8.
*
* @param data the iterable
* @return the size of the iterable
*/
public static long sizeUsingJava8(final Iterable data) {
return StreamSupport.stream(data.spliterator(), false).count();
}
/**
* Get the size of {@code Iterable} using Apache Collections.
*
* @param data the iterable
* @return the size of the iterable
*/
public static int sizeUsingApacheCollections(final Iterable data) {
return IterableUtils.size(data);
}
/**
* Get the size of {@code Iterable} using Google Guava.
*
* @param data the iterable
* @return the size of the iterable
*/
public static int sizeUsingGoogleGuava(final Iterable data) {
return Iterables.size(data);
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.java.list;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("baeldung");
vector.add("Vector");
vector.add("example");
Enumeration e = vector.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
Iterator<String> iterator = vector.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.java.sort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionsSortCompare {
public static void main(String[] args) {
sortPrimitives();
sortReferenceType();
sortCollection();
}
private static void sortReferenceType() {
Integer[] numbers = {5, 22, 10, 0};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
private static void sortCollection() {
List<Integer> numbersList = new ArrayList<>();
numbersList.add(5);
numbersList.add(22);
numbersList.add(10);
numbersList.add(0);
Collections.sort(numbersList);
numbersList.forEach(System.out::print);
}
private static void sortPrimitives() {
int[] numbers = {5, 22, 10, 0};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
/**
* This method shows how to make a null safe stream from a collection through the use of
* emptyIfNull() method from Apache Commons CollectionUtils library
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return emptyIfNull(collection).stream();
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
/**
* This method shows how to make a null safe stream from a collection through the use of
* Java SE 8s Optional Container
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return Optional.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
/**
* This method shows how to make a null safe stream from a collection through the use of a check
* to prevent null dereferences
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return collection == null ? Stream.empty() : collection.stream();
}
}

View File

@@ -0,0 +1,90 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10)
public class ArrayListBenchmark {
@State(Scope.Thread)
public static class MyState {
List<Employee> employeeList = new ArrayList<>();
Vector<Employee> employeeVector = new Vector<>();
//LinkedList<Employee> employeeList = new LinkedList<>();
long iterations = 100000;
Employee employee = new Employee(100L, "Harry");
int employeeIndex = -1;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeList.add(new Employee(i, "John"));
employeeVector.add(new Employee(i, "John"));
}
employeeList.add(employee);
employeeVector.add(employee);
employeeIndex = employeeList.indexOf(employee);
}
}
@Benchmark
public void testAddAt(ArrayListBenchmark.MyState state) {
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
}
@Benchmark
public boolean testContains(ArrayListBenchmark.MyState state) {
return state.employeeList.contains(state.employee);
}
@Benchmark
public boolean testContainsVector(ArrayListBenchmark.MyState state) {
return state.employeeVector.contains(state.employee);
}
@Benchmark
public int testIndexOf(ArrayListBenchmark.MyState state) {
return state.employeeList.indexOf(state.employee);
}
@Benchmark
public Employee testGet(ArrayListBenchmark.MyState state) {
return state.employeeList.get(state.employeeIndex);
}
@Benchmark
public Employee testVectorGet(ArrayListBenchmark.MyState state) {
return state.employeeVector.get(state.employeeIndex);
}
@Benchmark
public boolean testRemove(ArrayListBenchmark.MyState state) {
return state.employeeList.remove(state.employee);
}
@Benchmark
public void testAdd(ArrayListBenchmark.MyState state) {
state.employeeList.add(new Employee(state.iterations + 1, "John"));
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(ArrayListBenchmark.class.getSimpleName()).threads(3)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.performance;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Measurement(batchSize = 100000, iterations = 10)
@Warmup(batchSize = 100000, iterations = 10)
public class ArraySortBenchmark {
@State(Scope.Thread)
public static class Initialize {
Integer[] numbers = { -769214442, -1283881723, 1504158300, -1260321086, -1800976432, 1278262737, 1863224321, 1895424914, 2062768552, -1051922993, 751605209, -1500919212, 2094856518, -1014488489, -931226326, -1677121986, -2080561705, 562424208, -1233745158, 41308167 };
int[] primitives = { -769214442, -1283881723, 1504158300, -1260321086, -1800976432, 1278262737, 1863224321, 1895424914, 2062768552, -1051922993, 751605209, -1500919212, 2094856518, -1014488489, -931226326, -1677121986, -2080561705, 562424208, -1233745158, 41308167 };
}
@Benchmark
public Integer[] benchmarkArraysIntegerSort(ArraySortBenchmark.Initialize state) {
Arrays.sort(state.numbers);
return state.numbers;
}
@Benchmark
public int[] benchmarkArraysIntSort(ArraySortBenchmark.Initialize state) {
Arrays.sort(state.primitives);
return state.primitives;
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(ArraySortBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5)
public class CollectionsBenchmark {
@State(Scope.Thread)
public static class MyState {
private Set<Employee> employeeSet = new HashSet<>();
private List<Employee> employeeList = new ArrayList<>();
private long iterations = 10000;
private Employee employee = new Employee(100L, "Harry");
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeSet.add(new Employee(i, "John"));
employeeList.add(new Employee(i, "John"));
}
employeeList.add(employee);
employeeSet.add(employee);
}
}
@Benchmark
public boolean testArrayList(MyState state) {
return state.employeeList.contains(state.employee);
}
@Benchmark
public boolean testHashSet(MyState state) {
return state.employeeSet.contains(state.employee);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(CollectionsBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,78 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 10)
public class CopyOnWriteBenchmark {
@State(Scope.Thread)
public static class MyState {
CopyOnWriteArrayList<Employee> employeeList = new CopyOnWriteArrayList<>();
long iterations = 100000;
Employee employee = new Employee(100L, "Harry");
int employeeIndex = -1;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeList.add(new Employee(i, "John"));
}
employeeList.add(employee);
employeeIndex = employeeList.indexOf(employee);
}
}
@Benchmark
public void testAdd(CopyOnWriteBenchmark.MyState state) {
state.employeeList.add(new Employee(state.iterations + 1, "John"));
}
@Benchmark
public void testAddAt(CopyOnWriteBenchmark.MyState state) {
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
}
@Benchmark
public boolean testContains(CopyOnWriteBenchmark.MyState state) {
return state.employeeList.contains(state.employee);
}
@Benchmark
public int testIndexOf(CopyOnWriteBenchmark.MyState state) {
return state.employeeList.indexOf(state.employee);
}
@Benchmark
public Employee testGet(CopyOnWriteBenchmark.MyState state) {
return state.employeeList.get(state.employeeIndex);
}
@Benchmark
public boolean testRemove(CopyOnWriteBenchmark.MyState state) {
return state.employeeList.remove(state.employee);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.performance;
public class Employee {
private Long id;
private String name;
public Employee(Long id, String name) {
this.name = name;
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (!id.equals(employee.id)) return false;
return name.equals(employee.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 10)
public class HashMapBenchmark {
@State(Scope.Thread)
public static class MyState {
Map<Long, Employee> employeeMap = new HashMap<>();
//LinkedHashMap<Long, Employee> employeeMap = new LinkedHashMap<>();
//IdentityHashMap<Long, Employee> employeeMap = new IdentityHashMap<>();
//WeakHashMap<Long, Employee> employeeMap = new WeakHashMap<>();
//ConcurrentHashMap<Long, Employee> employeeMap = new ConcurrentHashMap<>();
//ConcurrentSkipListMap<Long, Employee> employeeMap = new ConcurrentSkipListMap <>();
// TreeMap
long iterations = 100000;
Employee employee = new Employee(100L, "Harry");
int employeeIndex = -1;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeMap.put(i, new Employee(i, "John"));
}
//employeeMap.put(iterations, employee);
}
}
@Benchmark
public Employee testGet(HashMapBenchmark.MyState state) {
return state.employeeMap.get(state.iterations);
}
@Benchmark
public Employee testRemove(HashMapBenchmark.MyState state) {
return state.employeeMap.remove(state.iterations);
}
@Benchmark
public Employee testPut(HashMapBenchmark.MyState state) {
return state.employeeMap.put(state.employee.getId(), state.employee);
}
@Benchmark
public Boolean testContainsKey(HashMapBenchmark.MyState state) {
return state.employeeMap.containsKey(state.employee.getId());
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(HashMapBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,66 @@
package com.baeldung.performance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 10)
public class SetBenchMark {
@State(Scope.Thread)
public static class MyState {
//Set<Employee> employeeSet = new HashSet<>();
LinkedHashSet<Employee> employeeSet = new LinkedHashSet<>();
//ConcurrentSkipListSet<Employee> employeeSet = new ConcurrentSkipListSet <>();
// TreeSet 
long iterations = 1000;
Employee employee = new Employee(100L, "Harry");
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeSet.add(new Employee(i, "John"));
}
//employeeSet.add(employee);
}
}
@Benchmark
public boolean testAdd(SetBenchMark.MyState state) {
return state.employeeSet.add(state.employee);
}
@Benchmark
public Boolean testContains(SetBenchMark.MyState state) {
return state.employeeSet.contains(state.employee);
}
@Benchmark
public boolean testRemove(SetBenchMark.MyState state) {
return state.employeeSet.remove(state.employee);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(SetBenchMark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.queueInterface;
import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.LinkedList;
public class CustomBaeldungQueue<T> extends AbstractQueue<T> {
private LinkedList<T> elements;
public CustomBaeldungQueue() {
this.elements = new LinkedList<T>();
}
@Override
public Iterator<T> iterator() {
return elements.iterator();
}
@Override
public int size() {
return elements.size();
}
@Override
public boolean offer(T t) {
if(t == null) return false;
elements.add(t);
return true;
}
@Override
public T poll() {
Iterator<T> iter = elements.iterator();
T t = iter.next();
if(t != null){
iter.remove();
return t;
}
return null;
}
@Override
public T peek() {
return elements.getFirst();
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.removal;
import java.util.ArrayList;
import java.util.Collection;
public class CollectionRemoveIf {
public static void main(String args[]) {
Collection<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
names.removeIf(e -> e.startsWith("A"));
System.out.println(String.join(",", names));
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.removal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Iterators {
public static void main(String args[]) {
Collection<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Iterator<String> i = names.iterator();
while (i.hasNext()) {
String e = i.next();
if (e.startsWith("A")) {
i.remove();
}
}
System.out.println(String.join(",", names));
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.removal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;
public class StreamFilterAndCollector {
public static void main(String args[]) {
Collection<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Collection<String> filteredCollection = names
.stream()
.filter(e -> !e.startsWith("A"))
.collect(Collectors.toList());
System.out.println(String.join(",", filteredCollection));
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.removal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamPartitioningBy {
public static void main(String args[]) {
Collection<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Map<Boolean, List<String>> classifiedElements = names
.stream()
.collect(Collectors.partitioningBy((String e) -> !e.startsWith("A")));
String matching = String.join(",", classifiedElements.get(Boolean.TRUE));
String nonMatching = String.join(",", classifiedElements.get(Boolean.FALSE));
System.out.println("Matching elements: " + matching);
System.out.println("Non matching elements: " + nonMatching);
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.synchronizedcollections.application;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
public class Application {
private static final Logger LOGGER = Logger.getLogger(Application.class.getName());
public static void main(String[] args) throws InterruptedException {
List<Integer> syncCollection = Collections.synchronizedList(Arrays.asList(1, 2, 3, 4, 5, 6));
synchronized (syncCollection) {
syncCollection.forEach((e) -> {LOGGER.info(e.toString());});
}
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.thread_safe_lifo;
import java.util.ArrayDeque;
/**
* Deque Based Stack implementation.
*/
public class DequeBasedSynchronizedStack<T> {
// Internal Deque which gets decorated for synchronization.
private ArrayDeque<T> dequeStore = new ArrayDeque<>();
public DequeBasedSynchronizedStack(int initialCapacity) {
this.dequeStore = new ArrayDeque<>(initialCapacity);
}
public DequeBasedSynchronizedStack() {
}
public synchronized T pop() {
return this.dequeStore.pop();
}
public synchronized void push(T element) {
this.dequeStore.push(element);
}
public synchronized T peek() {
return this.dequeStore.peek();
}
public synchronized int size() {
return this.dequeStore.size();
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,50 @@
package com.baeldung.arraydeque;
import java.util.ArrayDeque;
import java.util.Deque;
import static org.junit.Assert.*;
import org.junit.Test;
public class ArrayDequeUnitTest {
@Test
public void whenOffer_addsAtLast() {
final Deque<String> deque = new ArrayDeque<>();
deque.offer("first");
deque.offer("second");
assertEquals("second", deque.getLast());
}
@Test
public void whenPoll_removesFirst() {
final Deque<String> deque = new ArrayDeque<>();
deque.offer("first");
deque.offer("second");
assertEquals("first", deque.poll());
}
@Test
public void whenPush_addsAtFirst() {
final Deque<String> deque = new ArrayDeque<>();
deque.push("first");
deque.push("second");
assertEquals("second", deque.getFirst());
}
@Test
public void whenPop_removesLast() {
final Deque<String> deque = new ArrayDeque<>();
deque.push("first");
deque.push("second");
assertEquals("second", deque.pop());
}
}

View File

@@ -0,0 +1,50 @@
package com.baeldung.charstack;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
public class CharStackUnitTest {
@Test
public void whenCharStackIsCreated_thenItHasSize0() {
CharStack charStack = new CharStack();
assertEquals(0, charStack.size());
}
@Test
public void givenEmptyCharStack_whenElementIsPushed_thenStackSizeisIncreased() {
CharStack charStack = new CharStack();
charStack.push('A');
assertEquals(1, charStack.size());
}
@Test
public void givenCharStack_whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() {
CharStack charStack = new CharStack();
charStack.push('A');
char element = charStack.pop();
assertEquals('A', element);
assertEquals(0, charStack.size());
}
@Test
public void givenCharStack_whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() {
CharStack charStack = new CharStack();
charStack.push('A');
char element = charStack.peek();
assertEquals('A', element);
assertEquals(1, charStack.size());
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.charstack;
import static org.junit.Assert.assertEquals;
import java.util.Stack;
import org.junit.jupiter.api.Test;
public class CharStackUsingJavaUnitTest {
@Test
public void whenCharStackIsCreated_thenItHasSize0() {
Stack<Character> charStack = new Stack<>();
assertEquals(0, charStack.size());
}
@Test
public void givenEmptyCharStack_whenElementIsPushed_thenStackSizeisIncreased() {
Stack<Character> charStack = new Stack<>();
charStack.push('A');
assertEquals(1, charStack.size());
}
@Test
public void givenCharStack_whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() {
Stack<Character> charStack = new Stack<>();
charStack.push('A');
char element = charStack.pop();
assertEquals('A', element);
assertEquals(0, charStack.size());
}
@Test
public void givenCharStack_whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() {
Stack<Character> charStack = new Stack<>();
charStack.push('A');
char element = charStack.peek();
assertEquals('A', element);
assertEquals(1, charStack.size());
}
}

View File

@@ -0,0 +1,65 @@
package com.baeldung.charstack;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
public class CharStackWithArrayUnitTest {
@Test
public void whenCharStackIsCreated_thenItHasSize0() {
CharStackWithArray charStack = new CharStackWithArray();
assertEquals(0, charStack.size());
}
@Test
public void givenEmptyCharStack_whenElementIsPushed_thenStackSizeisIncreased() {
CharStackWithArray charStack = new CharStackWithArray();
charStack.push('A');
assertEquals(1, charStack.size());
}
@Test
public void givenEmptyCharStack_when5ElementIsPushed_thenStackSizeis() {
CharStackWithArray charStack = new CharStackWithArray();
charStack.push('A');
charStack.push('B');
charStack.push('C');
charStack.push('D');
charStack.push('E');
assertEquals(5, charStack.size());
}
@Test
public void givenCharStack_whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() {
CharStackWithArray charStack = new CharStackWithArray();
charStack.push('A');
char element = charStack.pop();
assertEquals('A', element);
assertEquals(0, charStack.size());
}
@Test
public void givenCharStack_whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() {
CharStackWithArray charStack = new CharStackWithArray();
charStack.push('A');
char element = charStack.peek();
assertEquals('A', element);
assertEquals(1, charStack.size());
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.combiningcollections;
import static org.junit.Assert.*;
import org.junit.Test;
public class CombiningArraysUnitTest {
private static final String first[] = {
"One",
"Two",
"Three"
};
private static final String second[] = {
"Four",
"Five",
"Six"
};
private static final String expected[] = {
"One",
"Two",
"Three",
"Four",
"Five",
"Six"
};
@Test
public void givenTwoArrays_whenUsingNativeJava_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingNativeJava(first, second));
}
@Test
public void givenTwoArrays_whenUsingObjectStreams_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingJava8ObjectStream(first, second));
}
@Test
public void givenTwoArrays_whenUsingFlatMaps_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingJava8FlatMaps(first, second));
}
@Test
public void givenTwoArrays_whenUsingApacheCommons_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingApacheCommons(first, second));
}
@Test
public void givenTwoArrays_whenUsingGuava_thenArraysCombined() {
assertArrayEquals(expected, CombiningArrays.usingGuava(first, second));
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class CombiningListsUnitTest {
private static final List<Object> first = Arrays.asList(new Object[]{
"One",
"Two",
"Three"
});
private static final List<Object> second = Arrays.asList(new Object[]{
"Four",
"Five",
"Six"
});
private static final List<Object> expected = Arrays.asList(new Object[]{
"One",
"Two",
"Three",
"Four",
"Five",
"Six"
});
@Test
public void givenTwoLists_whenUsingNativeJava_thenArraysCombined() {
assertThat(CombiningLists.usingNativeJava(first, second), is(expected));
}
@Test
public void givenTwoLists_whenUsingObjectStreams_thenArraysCombined() {
assertThat(CombiningLists.usingJava8ObjectStream(first, second), is(expected));
}
@Test
public void givenTwoLists_whenUsingFlatMaps_thenArraysCombined() {
assertThat(CombiningLists.usingJava8FlatMaps(first, second), is(expected));
}
@Test
public void givenTwoLists_whenUsingApacheCommons_thenArraysCombined() {
assertThat(CombiningLists.usingApacheCommons(first, second), is(expected));
}
@Test
public void givenTwoLists_whenUsingGuava_thenArraysCombined() {
assertThat(CombiningLists.usingGuava(first, second), is(expected));
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class CombiningMapsUnitTest {
private static final Map<String, String> first = new HashMap<>();
private static final Map<String, String> second = new HashMap<>();
private static Map<String, String> expected = new HashMap<>();
static {
first.put("one", "first String");
first.put("two", "second String");
second.put("three", "third String");
second.put("four", "fourth String");
expected.put("one", "first String");
expected.put("two", "second String");
expected.put("three", "third String");
expected.put("four", "fourth String");
}
@Test
public void givenTwoMaps_whenUsingNativeJava_thenMapsCombined() {
assertThat(CombiningMaps.usingPlainJava(first, second), is(expected));
}
@Test
public void givenTwoMaps_whenUsingForEach_thenMapsCombined() {
assertThat(CombiningMaps.usingJava8ForEach(first, second), is(expected));
}
@Test
public void givenTwoMaps_whenUsingFlatMaps_thenMapsCombined() {
assertThat(CombiningMaps.usingJava8FlatMaps(first, second), is(expected));
}
@Test
public void givenTwoMaps_whenUsingApacheCommons_thenMapsCombined() {
assertThat(CombiningMaps.usingApacheCommons(first, second), is(expected));
}
@Test
public void givenTwoMaps_whenUsingGuava_thenMapsCombined() {
assertThat(CombiningMaps.usingGuava(first, second), is(expected));
}
}

View File

@@ -0,0 +1,45 @@
package com.baeldung.combiningcollections;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class CombiningSetsUnitTest {
private static final Set<Object> first = new HashSet<Object>(Arrays.asList(new Object[] { "One", "Two", "Three" }));
private static final Set<Object> second = new HashSet<Object>(Arrays.asList(new Object[] { "Four", "Five", "Six" }));
private static final Set<Object> expected = new HashSet<Object>(Arrays
.asList(new Object[] { "One", "Two", "Three", "Four", "Five", "Six" }));
@Test
public void givenTwoSets_whenUsingNativeJava_thenArraysCombined() {
assertThat(CombiningSets.usingNativeJava(first, second), is(expected));
}
@Test
public void givenTwoSets_whenUsingObjectStreams_thenArraysCombined() {
assertThat(CombiningSets.usingJava8ObjectStream(first, second), is(expected));
}
@Test
public void givenTwoSets_whenUsingFlatMaps_thenArraysCombined() {
assertThat(CombiningSets.usingJava8FlatMaps(first, second), is(expected));
}
@Test
public void givenTwoSets_whenUsingApacheCommons_thenArraysCombined() {
assertThat(CombiningSets.usingApacheCommons(first, second), is(expected));
}
@Test
public void givenTwoSets_whenUsingGuava_thenArraysCombined() {
assertThat(CombiningSets.usingGuava(first, second), is(expected));
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.enummap;
/**
* This enum is used for benchmarking, therefore has many values.
*/
public enum DummyEnum {
CCC_000,
CCC_001,CCC_002,CCC_003,CCC_004,CCC_005,CCC_006,CCC_007,CCC_008,CCC_009,CCC_010,
CCC_011,CCC_012,CCC_013,CCC_014,CCC_015,CCC_016,CCC_017,CCC_018,CCC_019,CCC_020,
CCC_021,CCC_022,CCC_023,CCC_024,CCC_025,CCC_026,CCC_027,CCC_028,CCC_029,CCC_030,
CCC_031,CCC_032,CCC_033,CCC_034,CCC_035,CCC_036,CCC_037,CCC_038,CCC_039,CCC_040,
CCC_041,CCC_042,CCC_043,CCC_044,CCC_045,CCC_046,CCC_047,CCC_048,CCC_049,
}

View File

@@ -0,0 +1,119 @@
package com.baeldung.enummap;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode({ Mode.AverageTime })
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
public class EnumMapBenchmarkLiveTest {
@State(Scope.Thread)
public static class BenchmarkState {
EnumMap<DummyEnum, String> enumMap = new EnumMap<>(DummyEnum.class);
HashMap<DummyEnum, String> hashMap = new HashMap<>();
TreeMap<DummyEnum, String> treeMap = new TreeMap<>();
int len = DummyEnum.values().length;
Random random = new Random();
int randomIndex;
@Setup(Level.Trial)
public void setUp() {
DummyEnum[] values = DummyEnum.values();
for (int i = 0; i < len; i++) {
enumMap.put(values[i], values[i].toString());
hashMap.put(values[i], values[i].toString());
treeMap.put(values[i], values[i].toString());
}
}
@Setup(Level.Invocation)
public void additionalSetup() {
randomIndex = random.nextInt(len);
}
}
@Benchmark
public int benchmark01_EnumMapPut(BenchmarkState s) {
s.enumMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark01_HashMapPut(BenchmarkState s) {
s.hashMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark01_TreeMapPut(BenchmarkState s) {
s.treeMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark02_EnumMapGet(BenchmarkState s) {
s.enumMap.get(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark02_HashMapGet(BenchmarkState s) {
s.hashMap.get(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark02_TreeMapGet(BenchmarkState s) {
s.treeMap.get(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark03_EnumMapContainsKey(BenchmarkState s) {
s.enumMap.containsKey(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark03_HashMapContainsKey(BenchmarkState s) {
s.hashMap.containsKey(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark03_TreeMapContainsKey(BenchmarkState s) {
s.treeMap.containsKey(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark04_EnumMapContainsValue(BenchmarkState s) {
s.enumMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark04_HashMapContainsValue(BenchmarkState s) {
s.hashMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark04_TreeMapContainsValue(BenchmarkState s) {
s.treeMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(EnumMapBenchmarkLiveTest.class.getSimpleName()).threads(1).forks(0).shouldFailOnError(true).shouldDoGC(false).jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,144 @@
package com.baeldung.enummap;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static java.util.AbstractMap.SimpleEntry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
public class EnumMapUnitTest {
public enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
@Test
public void whenContructedWithEnumType_ThenOnlyAcceptThatAsKey() {
Map dayMap = new EnumMap<>(DayOfWeek.class);
assertThatCode(
() -> dayMap.put(TimeUnit.NANOSECONDS, "NANOSECONDS"))
.isInstanceOf(ClassCastException.class);
}
@Test
public void whenConstructedWithEnumMap_ThenSameKeyTypeAndInitialMappings() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");
EnumMap<DayOfWeek, String> activityMapCopy = new EnumMap<>(activityMap);
assertThat(activityMapCopy.size()).isEqualTo(2);
assertThat(activityMapCopy.get(DayOfWeek.MONDAY))
.isEqualTo("Soccer");
assertThat(activityMapCopy.get(DayOfWeek.TUESDAY))
.isEqualTo("Basketball");
}
@Test
public void givenEmptyMap_whenConstructedWithMap_ThenException() {
HashMap ordinaryMap = new HashMap();
assertThatCode(() -> new EnumMap(ordinaryMap))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Specified map is empty");
}
@Test
public void givenMapWithEntries_whenConstructedWithMap_ThenSucceed() {
HashMap<DayOfWeek, String> ordinaryMap = new HashMap<>();
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");
ordinaryMap.put(DayOfWeek.TUESDAY, "Basketball");
EnumMap<DayOfWeek, String> enumMap = new EnumMap<>(ordinaryMap);
assertThat(enumMap.size()).isEqualTo(2);
assertThat(enumMap.get(DayOfWeek.MONDAY)).isEqualTo("Soccer");
assertThat(enumMap.get(DayOfWeek.TUESDAY)).isEqualTo("Basketball");
}
@Test
public void givenMapWithMultiTypeEntries_whenConstructedWithMap_ThenException() {
HashMap<Enum, String> ordinaryMap = new HashMap<>();
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");
ordinaryMap.put(TimeUnit.MILLISECONDS, "Other enum type");
assertThatCode(() -> new EnumMap(ordinaryMap))
.isInstanceOf(ClassCastException.class);
}
@Test
public void whenPut_thenGet() {
Map<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
activityMap.put(DayOfWeek.THURSDAY, null);
assertThat(activityMap.get(DayOfWeek.WEDNESDAY)).isEqualTo("Hiking");
assertThat(activityMap.get(DayOfWeek.THURSDAY)).isNull();
}
@Test
public void givenMapping_whenContains_thenTrue() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isFalse();
assertThat(activityMap.containsValue("Hiking")).isFalse();
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isTrue();
assertThat(activityMap.containsValue("Hiking")).isTrue();
assertThat(activityMap.containsKey(DayOfWeek.SATURDAY)).isFalse();
assertThat(activityMap.containsValue(null)).isFalse();
activityMap.put(DayOfWeek.SATURDAY, null);
assertThat(activityMap.containsKey(DayOfWeek.SATURDAY)).isTrue();
assertThat(activityMap.containsValue(null)).isTrue();
}
@Test
public void whenRemove_thenRemoved() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
assertThat(activityMap.remove(DayOfWeek.MONDAY)).isEqualTo("Soccer");
assertThat(activityMap.containsKey(DayOfWeek.MONDAY)).isFalse();
activityMap.put(DayOfWeek.MONDAY, "Soccer");
assertThat(activityMap.remove(DayOfWeek.MONDAY, "Hiking")).isEqualTo(false);
assertThat(activityMap.remove(DayOfWeek.MONDAY, "Soccer")).isEqualTo(true);
}
@Test
public void whenSubView_thenSubViewOrdered() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
activityMap.put(DayOfWeek.THURSDAY, "Karate");
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
activityMap.put(DayOfWeek.MONDAY, "Soccer");
Collection<String> values = activityMap.values();
assertThat(values).containsExactly("Soccer", "Hiking", "Karate");
Set<DayOfWeek> keys = activityMap.keySet();
assertThat(keys)
.containsExactly(DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY,DayOfWeek.THURSDAY);
assertThat(activityMap.entrySet())
.containsExactly(
new SimpleEntry(DayOfWeek.MONDAY, "Soccer"),
new SimpleEntry(DayOfWeek.WEDNESDAY, "Hiking"),
new SimpleEntry(DayOfWeek.THURSDAY, "Karate"));
}
@Test
public void givenSubView_whenChange_thenReflected() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
activityMap.put(DayOfWeek.THURSDAY, "Karate");
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
activityMap.put(DayOfWeek.MONDAY, "Soccer");
Collection<String> values = activityMap.values();
assertThat(values).containsExactly("Soccer", "Hiking", "Karate");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");
assertThat(values)
.containsExactly("Soccer", "Basketball", "Hiking", "Karate");
values.remove("Hiking");
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isFalse();
assertThat(activityMap.size()).isEqualTo(3);
}
}

View File

@@ -0,0 +1,98 @@
package com.baeldung.hashmapvshashtable;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Test;
import com.google.common.collect.Lists;
public class HashmapVsHashtableDifferenceUnitTest {
// null values
@Test(expected = NullPointerException.class)
public void givenHashtable_whenAddNullKey_thenNullPointerExceptionThrown() {
Hashtable<String, String> table = new Hashtable<String, String>();
table.put(null, "value");
}
@Test(expected = NullPointerException.class)
public void givenHashtable_whenAddNullValue_thenNullPointerExceptionThrown() {
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("key", null);
}
@Test
public void givenHashmap_whenAddNullKeyAndValue_thenObjectAdded() {
HashMap<String, String> map = new HashMap<String, String>();
map.put(null, "value");
map.put("key1", null);
map.put("key2", null);
assertEquals(3, map.size());
}
// fail-fast iterator
@Test(expected = ConcurrentModificationException.class)
public void givenHashmap_whenModifyUnderlyingCollection_thenConcurrentModificationExceptionThrown() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Iterator<String> iterator = map.keySet().iterator();
while(iterator.hasNext()){
iterator.next();
map.put("key4", "value4");
}
}
@Test
public void givenHashtable_whenModifyUnderlyingCollection_thenItHasNoEffectOnIteratedCollection() {
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("key1", "value1");
table.put("key2", "value2");
List<String> keysSelected = Lists.newArrayList();
Enumeration<String> keys = table.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
keysSelected.add(key);
if (key.equals("key1")) {
table.put("key3", "value3");
}
}
assertEquals(2, keysSelected.size());
}
// synchronized map
@Test
public void givenHashmap_thenCreateSynchronizedMap() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Set<Entry<String, String>> set = map.entrySet();
synchronized (map) {
Iterator<Entry<String, String>> it = set.iterator();
while(it.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>)it.next();
}
}
Map<String, String> syncMap = Collections.synchronizedMap(map);
}
}

View File

@@ -0,0 +1,274 @@
package com.baeldung.hashtable;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
public class HashtableUnitTest {
@Test
public void whenPutAndGet_thenReturnsValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
Word word = new Word("cat");
table.put(word, "an animal");
String definition = table.get(word);
assertEquals("an animal", definition);
definition = table.remove(word);
assertEquals("an animal", definition);
}
@Test
public void whenThesameInstanceOfKey_thenReturnsValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
Word word = new Word("cat");
table.put(word, "an animal");
String extracted = table.get(word);
assertEquals("an animal", extracted);
}
@Test
public void whenEqualsOverridden_thenReturnsValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
Word word = new Word("cat");
table.put(word, "an animal");
String extracted = table.get(new Word("cat"));
assertEquals("an animal", extracted);
}
@Test(expected = NullPointerException.class)
public void whenNullKey_thenException() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(null, "an animal");
}
@Test(expected = ConcurrentModificationException.class)
public void whenIterate_thenFailFast() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "an animal");
table.put(new Word("dog"), "another animal");
Iterator<Word> it = table.keySet().iterator();
System.out.println("iterator created");
table.remove(new Word("dog"));
System.out.println("element removed");
while (it.hasNext()) {
Word key = it.next();
System.out.println(table.get(key));
}
}
@Test
public void whenEnumerate_thenNotFailFast() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("1"), "one");
table.put(new Word("2"), "two");
table.put(new Word("3"), "three");
table.put(new Word("4"), "four");
table.put(new Word("5"), "five");
table.put(new Word("6"), "six");
table.put(new Word("7"), "seven");
table.put(new Word("8"), "eight");
Enumeration<Word> enumKey = table.keys();
System.out.println("Enumeration created");
table.remove(new Word("1"));
System.out.println("element removed");
while (enumKey.hasMoreElements()) {
Word key = enumKey.nextElement();
System.out.println(table.get(key));
}
}
@Test
public void whenAddElements_thenIterationOrderUnpredicable() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("1"), "one");
table.put(new Word("2"), "two");
table.put(new Word("3"), "three");
table.put(new Word("4"), "four");
table.put(new Word("5"), "five");
table.put(new Word("6"), "six");
table.put(new Word("7"), "seven");
table.put(new Word("8"), "eight");
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Word, String> entry = it.next();
System.out.println(entry.getValue());
}
}
@Test
public void whenGetOrDefault_thenDefaultGot() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
Word key = new Word("dog");
String definition;
// old way
/* if (table.containsKey(key)) {
definition = table.get(key);
} else {
definition = "not found";
}*/
// new way
definition = table.getOrDefault(key, "not found");
assertThat(definition, is("not found"));
}
@Test
public void whenPutifAbsent_thenNotRewritten() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
String definition = "an animal";
// old way
/* if (!table.containsKey(new Word("cat"))) {
table.put(new Word("cat"), definition);
}*/
// new way
table.putIfAbsent(new Word("cat"), definition);
assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal"));
}
@Test
public void whenRemovePair_thenCheckKeyAndValue() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
// old way
/* if (table.get(new Word("cat")).equals("an animal")) {
table.remove(new Word("cat"));
}*/
// new way
boolean result = table.remove(new Word("cat"), "an animal");
assertThat(result, is(false));
}
@Test
public void whenReplacePair_thenValueChecked() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
String definition = "an animal";
// old way
/* if (table.containsKey(new Word("cat")) && table.get(new Word("cat")).equals("a small domesticated carnivorous mammal")) {
table.put(new Word("cat"), definition);
}*/
// new way
table.replace(new Word("cat"), "a small domesticated carnivorous mammal", definition);
assertThat(table.get(new Word("cat")), is("an animal"));
}
@Test
public void whenKeyIsAbsent_thenNotRewritten() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
// old way
/* if (!table.containsKey(cat)) {
String definition = "an animal";// calculate
table.put(new Word("cat"), definition);
}
*/
// new way
table.computeIfAbsent(new Word("cat"), key -> "an animal");
assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal"));
}
@Test
public void whenKeyIsPresent_thenComputeIfPresent() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
Word cat = new Word("cat");
// old way
/* if (table.containsKey(cat)) {
String concatination = cat.getName() + " - " + table.get(cat);
table.put(cat, concatination);
}*/
// new way
table.computeIfPresent(cat, (key, value) -> key.getName() + " - " + value);
assertThat(table.get(cat), is("cat - a small domesticated carnivorous mammal"));
}
@Test
public void whenCompute_thenForAllKeys() {
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
for (String animal : animals) {
table.compute(animal, (key, value) -> (value == null ? 1 : value + 1));
}
assertThat(table.values(), hasItems(2, 2, 2, 1));
}
@Test
public void whenInsteadOfCompute_thenMerge() {
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
for (String animal : animals) {
table.merge(animal, 1, (oldValue, value) -> (oldValue + value));
}
assertThat(table.values(), hasItems(2, 2, 2, 1));
}
@Test
public void whenForeach_thenIterate() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
table.put(new Word("dog"), "another animal");
table.forEach((k, v) -> System.out.println(k.getName() + " - " + v)
);
}
@Test
public void whenReplaceall_thenNoIterationNeeded() {
Hashtable<Word, String> table = new Hashtable<Word, String>();
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
table.put(new Word("dog"), "another animal");
table.replaceAll((k, v) -> k.getName() + " - " + v);
assertThat(table.values(), hasItems("cat - a small domesticated carnivorous mammal", "dog - another animal"));
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.iterators;
import static com.baeldung.iterators.Iterators.failFast1;
import static com.baeldung.iterators.Iterators.failFast2;
import static com.baeldung.iterators.Iterators.failSafe1;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ConcurrentModificationException;
import org.junit.Test;
/**
* Source code https://github.com/eugenp/tutorials
*
* @author Santosh Thakur
*/
public class IteratorsUnitTest {
@Test
public void whenFailFast_ThenThrowsException() {
assertThatThrownBy(() -> {
failFast1();
}).isInstanceOf(ConcurrentModificationException.class);
}
@Test
public void whenFailFast_ThenThrowsExceptionInSecondIteration() {
assertThatThrownBy(() -> {
failFast2();
}).isInstanceOf(ConcurrentModificationException.class);
}
@Test
public void whenFailSafe_ThenDoesNotThrowException() {
assertThat(failSafe1()).isGreaterThanOrEqualTo(0);
}
}

View File

@@ -0,0 +1,83 @@
package com.baeldung.java.collections;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class ConcurrentModificationExceptionUnitTest {
@Test
public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception {
ArrayList<Object> array = new ArrayList<>(asList(0, "one", 2, "three"));
for (Object item : array) {
array.set(3, 3);
}
}
@Test
public void removingElementUsingIteratorAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
Iterator<String> iterator = originalList.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (Objects.equals(next, "one")) iterator.remove();
}
assertEquals(originalList, asList("zero", "two", "three"));
}
@Test
public void modifyingContentAndIteratingUsingListIteratorAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
ListIterator<String> iterator = originalList.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (Objects.equals(next, "one")) {
iterator.set("another");
}
if (Objects.equals(next, "two")) {
iterator.remove();
}
if (Objects.equals(next, "three")) {
iterator.add("four");
}
}
assertEquals(originalList, asList("zero", "another", "three", "four"));
}
@Test
public void removingElementUsingCopyAndListAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
List<String> listCopy = new ArrayList<>(originalList);
for (String next : listCopy) {
if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
}
assertEquals(originalList, asList("one", "two", "three"));
}
@Test
public void copyOnWriteList() throws Exception {
List<String> originalList = new CopyOnWriteArrayList<>(asList("zero", "one", "two", "three"));
for (String next : originalList) {
if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
}
assertEquals(originalList, asList("one", "two", "three"));
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.java.filtering;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
public class CollectionFiltersUnitTest {
private static final Collection<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8);
private static final Collection<Integer> EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8);
@Test
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
final Collection<String> baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other");
Collection<String> filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4);
assertThat(filtered).containsExactlyInAnyOrder("java", "type");
}
@Test
public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() {
Collection<Integer> filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION));
Collection<Integer> filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils)
.hasSameElementsAs(filteredWithEclipseCollections)
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
.hasSameElementsAs(filteredWithGuava)
.hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION);
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.java.iterable;
import static org.junit.Assert.assertEquals;
import java.sql.SQLException;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
class IterableSizeUnitTest {
private final List<String> list = Lists.newArrayList("Apple", "Orange", "Banana");
private Iterable data;
@Test
void whenUsingJava7_iterableOfCollectionType_thenCorrectSize() {
final int size = IterableSize.sizeUsingJava7(list);
assertEquals(3, size);
}
@Test
void whenUsingJava7_iterableNotOfCollectionType_thenCorrect() {
final SQLException exception = new SQLException();
exception.setNextException(new SQLException());
final int size = IterableSize.sizeUsingJava7(exception);
assertEquals(2, size);
}
@Test
void whenUsingJava8_thenCorrect() {
final long size = IterableSize.sizeUsingJava8(list);
assertEquals(3, size);
}
@Test
void whenUsingApacheCollections_thenCorrect() {
final int size = IterableSize.sizeUsingApacheCollections(list);
assertEquals(3, size);
}
@Test
void whenUsingGoogleGuava_thenCorrect() {
final int size = IterableSize.sizeUsingGoogleGuava(list);
assertEquals(3, size);
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest {
private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
new NullSafeCollectionStreamsUsingNullDereferenceCheck();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.queueInterface;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class CustomBaeldungQueueUnitTest {
private CustomBaeldungQueue<Integer> customQueue;
@Before
public void setUp() throws Exception {
customQueue = new CustomBaeldungQueue<>();
}
@Test
public void givenQueueWithTwoElements_whenElementsRetrieved_checkRetrievalCorrect() {
customQueue.add(7);
customQueue.add(5);
int first = customQueue.poll();
int second = customQueue.poll();
assertEquals(7, first);
assertEquals(5, second);
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.queueInterface;
import org.junit.Before;
import org.junit.Test;
import java.util.PriorityQueue;
import static org.junit.Assert.assertEquals;
public class PriorityQueueUnitTest {
@Test
public void givenIntegerQueue_whenIntegersOutOfOrder_checkRetrievalOrderIsNatural() {
PriorityQueue<Integer> integerQueue = new PriorityQueue<>();
integerQueue.add(9);
integerQueue.add(2);
integerQueue.add(4);
int first = integerQueue.poll();
int second = integerQueue.poll();
int third = integerQueue.poll();
assertEquals(2, first);
assertEquals(4, second);
assertEquals(9, third);
}
@Test
public void givenStringQueue_whenStringsAddedOutOfNaturalOrder_checkRetrievalOrderNatural() {
PriorityQueue<String> stringQueue = new PriorityQueue<>();
stringQueue.add("banana");
stringQueue.add("apple");
stringQueue.add("cherry");
String first = stringQueue.poll();
String second = stringQueue.poll();
String third = stringQueue.poll();
assertEquals("apple", first);
assertEquals("banana", second);
assertEquals("cherry", third);
}
}

View File

@@ -0,0 +1,77 @@
package com.baeldung.removal;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class RemovalUnitTest {
Collection<String> names;
Collection<String> expected;
Collection<String> removed;
@Before
public void setupTestData() {
names = new ArrayList<>();
expected = new ArrayList<>();
removed = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
expected.add("John");
expected.add("Mary");
expected.add("Mark");
removed.add("Ana");
removed.add("Anthony");
}
@Test
public void givenCollectionOfNames_whenUsingIteratorToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
Iterator<String> i = names.iterator();
while (i.hasNext()) {
String e = i.next();
if (e.startsWith("A")) {
i.remove();
}
}
assertThat(names, is(expected));
}
@Test
public void givenCollectionOfNames_whenUsingRemoveIfToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
names.removeIf(e -> e.startsWith("A"));
assertThat(names, is(expected));
}
@Test
public void givenCollectionOfNames_whenUsingStreamToFilterAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
Collection<String> filteredCollection = names
.stream()
.filter(e -> !e.startsWith("A"))
.collect(Collectors.toList());
assertThat(filteredCollection, is(expected));
}
@Test
public void givenCollectionOfNames_whenUsingStreamAndPartitioningByToFindNamesThatStartWithLetterA_shouldFind3MatchingAnd2NonMatching() {
Map<Boolean, List<String>> classifiedElements = names
.stream()
.collect(Collectors.partitioningBy((String e) -> !e.startsWith("A")));
assertThat(classifiedElements.get(Boolean.TRUE), is(expected));
assertThat(classifiedElements.get(Boolean.FALSE), is(removed));
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.shufflingcollections;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class ShufflingCollectionsUnitTest {
@Test
public void whenShufflingList_thenListIsShuffled() {
List<String> students = Arrays.asList("Foo", "Bar", "Baz", "Qux");
System.out.println("List before shuffling:");
System.out.println(students);
Collections.shuffle(students);
System.out.println("List after shuffling:");
System.out.println(students);
}
@Test
public void whenShufflingMapEntries_thenValuesAreShuffled() {
Map<Integer, String> studentsById = new HashMap<>();
studentsById.put(1, "Foo");
studentsById.put(2, "Bar");
studentsById.put(3, "Baz");
studentsById.put(4, "Qux");
System.out.println("Students before shuffling:");
System.out.println(studentsById.values());
List<Map.Entry<Integer, String>> shuffledStudentEntries = new ArrayList<>(studentsById.entrySet());
Collections.shuffle(shuffledStudentEntries);
List<String> shuffledStudents = shuffledStudentEntries.stream()
.map(Map.Entry::getValue)
.collect(Collectors.toList());
System.out.println("Students after shuffling");
System.out.println(shuffledStudents);
}
@Test
public void whenShufflingSet_thenElementsAreShuffled() {
Set<String> students = new HashSet<>(Arrays.asList("Foo", "Bar", "Baz", "Qux"));
System.out.println("Set before shuffling:");
System.out.println(students);
List<String> studentList = new ArrayList<>(students);
Collections.shuffle(studentList);
System.out.println("Shuffled set elements:");
System.out.println(studentList);
}
@Test
public void whenShufflingWithSameRandomness_thenElementsAreShuffledDeterministically() {
List<String> students_1 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
List<String> students_2 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
Collections.shuffle(students_1, new Random(5));
Collections.shuffle(students_2, new Random(5));
assertThat(students_1).isEqualTo(students_2);
}
}

View File

@@ -0,0 +1,101 @@
package com.baeldung.stack_tests;
import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayDeque;
import java.util.concurrent.ConcurrentLinkedDeque;
import static java.util.stream.IntStream.range;
/**
* Correctness tests for Stack in multi threaded environment.
*/
public class MultithreadingCorrectnessStackUnitTest {
@Test
public void givenSynchronizedDeque_whenExecutedParallel_thenWorkRight() {
DequeBasedSynchronizedStack<Integer> deque = new DequeBasedSynchronizedStack<>();
// Serial execution of push on ConcurrentLinkedQueue will always result in correct execution.
range(1, 10000).forEach(value -> deque.push(value));
int sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
// Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution.
range(1, 10000).parallel().forEach(value -> deque.push(value));
sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
}
@Test
public void givenConcurrentLinkedQueue_whenExecutedParallel_thenWorkRight() {
ConcurrentLinkedDeque<Integer> deque = new ConcurrentLinkedDeque<>();
// Serial execution of push on ConcurrentLinkedQueue will always result in correct execution.
range(1, 10000).forEach(value -> deque.push(value));
int sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
// Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution.
range(1, 10000).parallel().forEach(value -> deque.push(value));
sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
}
@Test
public void givenArrayDeque_whenExecutedParallel_thenShouldFail() {
ArrayDeque<Integer> deque = new ArrayDeque<>();
// Serial execution of push on ArrayDeque will always result in correct execution.
range(1, 10000).forEach(value -> deque.push(value));
int sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
// Parallel execution of push on ArrayDeque will not result in correct execution.
range(1, 10000).parallel().forEach(value -> deque.push(value));
sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
// This shouldn't happen.
if(sum == 49995000) {
System.out.println("Something wrong in the environment, Please try some big value and check");
// To safe-guard build without test failures.
return;
}
Assert.assertNotEquals(49995000, sum);
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.stack_tests;
import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack;
import com.google.common.collect.Streams;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.Stack;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.stream.Stream;
import static java.util.stream.IntStream.range;
/**
* These tests are to understand the Stack implementation in Java Collections.
*/
public class StackUnitTest {
@Test
public void givenStack_whenPushPopPeek_thenWorkRight() {
Stack<String> namesStack = new Stack<>();
namesStack.push("Bill Gates");
namesStack.push("Elon Musk");
Assert.assertEquals("Elon Musk", namesStack.peek());
Assert.assertEquals("Elon Musk", namesStack.pop());
Assert.assertEquals("Bill Gates", namesStack.pop());
Assert.assertEquals(0, namesStack.size());
}
@Test
public void givenSynchronizedDeque_whenPushPopPeek_thenWorkRight() {
DequeBasedSynchronizedStack<String> namesStack = new DequeBasedSynchronizedStack<>();
namesStack.push("Bill Gates");
namesStack.push("Elon Musk");
Assert.assertEquals("Elon Musk", namesStack.peek());
Assert.assertEquals("Elon Musk", namesStack.pop());
Assert.assertEquals("Bill Gates", namesStack.pop());
Assert.assertEquals(0, namesStack.size());
}
@Test
public void givenConcurrentLinkedDeque_whenPushPopPeek_thenWorkRight() {
ConcurrentLinkedDeque<String> namesStack = new ConcurrentLinkedDeque<>();
namesStack.push("Bill Gates");
namesStack.push("Elon Musk");
Assert.assertEquals("Elon Musk", namesStack.peek());
Assert.assertEquals("Elon Musk", namesStack.pop());
Assert.assertEquals("Bill Gates", namesStack.pop());
Assert.assertEquals(0, namesStack.size());
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.synchronizedcollections.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class SynchronizedCollectionUnitTest {
@Test
public void givenSynchronizedCollection_whenTwoThreadsAddElements_thenCorrectCollectionSize() throws InterruptedException {
Collection<Integer> syncCollection = Collections.synchronizedCollection(new ArrayList<>());
Runnable listOperations = () -> {
syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
};
Thread thread1 = new Thread(listOperations);
Thread thread2 = new Thread(listOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncCollection.size()).isEqualTo(12);
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.synchronizedcollections.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class SynchronizedListUnitTest {
@Test
public void givenSynchronizedList_whenTwoThreadsAddElements_thenCorrectListSize() throws InterruptedException {
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
Runnable listOperations = () -> {
syncList.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
};
Thread thread1 = new Thread(listOperations);
Thread thread2 = new Thread(listOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncList.size()).isEqualTo(12);
}
@Test
public void givenStringList_whenTwoThreadsIterateOnSynchronizedList_thenCorrectResult() throws InterruptedException {
List<String> syncCollection = Collections.synchronizedList(Arrays.asList("a", "b", "c"));
List<String> uppercasedCollection = new ArrayList<>();
Runnable listOperations = () -> {
synchronized (syncCollection) {
syncCollection.forEach((e) -> {
uppercasedCollection.add(e.toUpperCase());
});
}
};
Thread thread1 = new Thread(listOperations);
Thread thread2 = new Thread(listOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(uppercasedCollection.get(0)).isEqualTo("A");
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.synchronizedcollections.test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class SynchronizedMapUnitTest {
@Test
public void givenSynchronizedMap_whenTwoThreadsAddElements_thenCorrectMapSize() throws InterruptedException {
Map<Integer, String> syncMap = Collections.synchronizedMap(new HashMap<>());
Runnable mapOperations = () -> {
syncMap.put(1, "one");
syncMap.put(2, "two");
syncMap.put(3, "three");
};
Thread thread1 = new Thread(mapOperations);
Thread thread2 = new Thread(mapOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncMap.size()).isEqualTo(3);
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.synchronizedcollections.test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class SynchronizedSetUnitTest {
@Test
public void givenSynchronizedSet_whenTwoThreadsAddElements_thenCorrectSetSize() throws InterruptedException {
Set<Integer> syncSet = Collections.synchronizedSet(new HashSet<>());
Runnable setOperations = () -> {syncSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));};
Thread thread1 = new Thread(setOperations);
Thread thread2 = new Thread(setOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncSet.size()).isEqualTo(6);
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.synchronizedcollections.test;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class SynchronizedSortedMapUnitTest {
@Test
public void givenSynchronizedSorteMap_whenTwoThreadsAddElements_thenCorrectSortedMapSize() throws InterruptedException {
Map<Integer, String> syncSortedMap = Collections.synchronizedSortedMap(new TreeMap<>());
Runnable sortedMapOperations = () -> {
syncSortedMap.put(1, "One");
syncSortedMap.put(2, "Two");
syncSortedMap.put(3, "Three");
};
Thread thread1 = new Thread(sortedMapOperations);
Thread thread2 = new Thread(sortedMapOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncSortedMap.size()).isEqualTo(3);
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.synchronizedcollections.test;
import java.util.Arrays;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class SynchronizedSortedSetUnitTest {
@Test
public void givenSynchronizedSortedSet_whenTwoThreadsAddElements_thenCorrectSortedSetSize() throws InterruptedException {
SortedSet<Integer> syncSortedSet = Collections.synchronizedSortedSet(new TreeSet<>());
Runnable sortedSetOperations = () -> {syncSortedSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));};
sortedSetOperations.run();
sortedSetOperations.run();
Thread thread1 = new Thread(sortedSetOperations);
Thread thread2 = new Thread(sortedSetOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncSortedSet.size()).isEqualTo(6);
}
}

View File

@@ -0,0 +1,135 @@
package org.baeldung.java.collections;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IterableUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
public class CollectionsConcatenateUnitTest {
@Test
public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Collection<String> collectionC = asList("W", "X");
Stream<String> combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream());
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined);
}
@Test
public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Stream<String> combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream);
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB));
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = concat(collectionA, collectionB);
Collection<String> collectionCombined = makeListFromIterable(combinedIterables);
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
}
public static <E> Iterable<E> concat(Iterable<? extends E> i1, Iterable<? extends E> i2) {
return new Iterable<E>() {
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<? extends E> listIterator = i1.iterator();
Boolean checkedHasNext;
E nextValue;
private boolean startTheSecond;
void theNext() {
if (listIterator.hasNext()) {
checkedHasNext = true;
nextValue = listIterator.next();
} else if (startTheSecond)
checkedHasNext = false;
else {
startTheSecond = true;
listIterator = i2.iterator();
theNext();
}
}
public boolean hasNext() {
if (checkedHasNext == null)
theNext();
return checkedHasNext;
}
public E next() {
if (!hasNext())
throw new NoSuchElementException();
checkedHasNext = null;
return nextValue;
}
public void remove() {
listIterator.remove();
}
};
}
};
}
public static <E> List<E> makeListFromIterable(Iterable<E> iter) {
List<E> list = new ArrayList<>();
for (E item : iter) {
list.add(item);
}
return list;
}
@Test
public void givenUsingApacheCommons_whenConcatenatingUsingUnion_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = CollectionUtils.union(collectionA, collectionB);
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingApacheCommons_whenConcatenatingUsingChainedIterable_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = IterableUtils.chainedIterable(collectionA, collectionB);
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
}

View File

@@ -0,0 +1,62 @@
package org.baeldung.java.collections;
import java.util.ArrayList;
import java.util.Collections;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CollectionsJoinAndSplitJUnitTest {
private ArrayList<String> sauces = new ArrayList<>();
private ArrayList<String> cheeses = new ArrayList<>();
private ArrayList<String> vegetables = new ArrayList<>();
private ArrayList<ArrayList<String>> ingredients = new ArrayList<>();
@Before
public void init() {
sauces.add("Olive Oil");
sauces.add("Marinara");
cheeses.add("Mozzarella");
cheeses.add("Feta");
cheeses.add("Parmesan");
vegetables.add("Olives");
vegetables.add("Spinach");
vegetables.add("Green Peppers");
ingredients.add(sauces);
ingredients.add(cheeses);
ingredients.add(vegetables);
}
@Test
public void givenThreeArrayLists_whenJoiningIntoOneArrayList_shouldSucceed() {
ArrayList<ArrayList<String>> toppings = new ArrayList<>();
toppings.add(sauces);
toppings.add(cheeses);
toppings.add(vegetables);
Assert.assertTrue(toppings.size() == 3);
Assert.assertTrue(toppings.contains(sauces));
Assert.assertTrue(toppings.contains(cheeses));
Assert.assertTrue(toppings.contains(vegetables));
}
@Test
public void givenOneArrayList_whenSplittingIntoTwoArrayLists_shouldSucceed() {
ArrayList<ArrayList<String>> removedToppings = new ArrayList<>();
removedToppings.add(ingredients.remove(ingredients.indexOf(vegetables)));
Assert.assertTrue(removedToppings.contains(vegetables));
Assert.assertTrue(removedToppings.size() == 1);
Assert.assertTrue(ingredients.size() == 2);
Assert.assertTrue(ingredients.contains(sauces));
Assert.assertTrue(ingredients.contains(cheeses));
}
}

View File

@@ -0,0 +1,154 @@
package org.baeldung.java.collections;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class JoinSplitCollectionsUnitTest {
@Test
public void whenJoiningTwoArrays_thenJoined() {
String[] animals1 = new String[] { "Dog", "Cat" };
String[] animals2 = new String[] { "Bird", "Cow" };
String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new);
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
}
@Test
public void whenJoiningTwoCollections_thenJoined() {
Collection<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose")));
}
@Test
public void whenJoiningTwoCollectionsWithFilter_thenJoined() {
Collection<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> result = Stream.concat(collection1.stream(), collection2.stream()).filter(e -> e.length() == 3).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow")));
}
@Test
public void whenConvertArrayToString_thenConverted() {
String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow" };
String result = Arrays.stream(animals).collect(Collectors.joining(", "));
assertEquals(result, "Dog, Cat, Bird, Cow");
}
@Test
public void whenConvertCollectionToString_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", "Bird", "Cow");
String result = animals.stream().collect(Collectors.joining(", "));
assertEquals(result, "Dog, Cat, Bird, Cow");
}
@Test
public void whenConvertMapToString_thenConverted() {
Map<Integer, String> animals = new HashMap<>();
animals.put(1, "Dog");
animals.put(2, "Cat");
animals.put(3, "Cow");
String result = animals.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()).collect(Collectors.joining(", "));
assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow");
}
@Test
public void whenConvertNestedCollectionToString_thenConverted() {
Collection<List<String>> nested = new ArrayList<>();
nested.add(Arrays.asList("Dog", "Cat"));
nested.add(Arrays.asList("Cow", "Pig"));
String result = nested.stream().map(nextList -> nextList.stream().collect(Collectors.joining("-"))).collect(Collectors.joining("; "));
assertEquals(result, "Dog-Cat; Cow-Pig");
}
@Test
public void whenConvertCollectionToStringAndSkipNull_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", null, "Moose");
String result = animals.stream().filter(Objects::nonNull).collect(Collectors.joining(", "));
assertEquals(result, "Dog, Cat, Moose");
}
@Test
public void whenSplitCollectionHalf_thenConverted() {
Collection<String> animals = Arrays.asList("Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
Collection<String> result1 = new ArrayList<>();
Collection<String> result2 = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
int midpoint = Math.round(animals.size() / 2);
animals.forEach(next -> {
int index = count.getAndIncrement();
if (index < midpoint) {
result1.add(next);
} else {
result2.add(next);
}
});
assertTrue(result1.equals(Arrays.asList("Dog", "Cat", "Cow")));
assertTrue(result2.equals(Arrays.asList("Bird", "Moose", "Pig")));
}
@Test
public void whenSplitArrayByWordLength_thenConverted() {
String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose" };
Map<Integer, List<String>> result = Arrays.stream(animals).collect(Collectors.groupingBy(String::length));
assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig")));
assertTrue(result.get(4).equals(Arrays.asList("Bird")));
assertTrue(result.get(5).equals(Arrays.asList("Moose")));
}
@Test
public void whenConvertStringToArray_thenConverted() {
String animals = "Dog, Cat, Bird, Cow";
String[] result = animals.split(", ");
assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" });
}
@Test
public void whenConvertStringToCollection_thenConverted() {
String animals = "Dog, Cat, Bird, Cow";
Collection<String> result = Arrays.asList(animals.split(", "));
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
}
@Test
public void whenConvertStringToMap_thenConverted() {
String animals = "1 = Dog, 2 = Cat, 3 = Bird";
Map<Integer, String> result = Arrays.stream(animals.split(", ")).map(next -> next.split(" = ")).collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1]));
assertEquals(result.get(1), "Dog");
assertEquals(result.get(2), "Cat");
assertEquals(result.get(3), "Bird");
}
@Test
public void whenConvertCollectionToStringMultipleSeparators_thenConverted() {
String animals = "Dog. , Cat, Bird. Cow";
Collection<String> result = Arrays.stream(animals.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
}
}

View File

@@ -0,0 +1,3 @@
### Relevant Articles:
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)

View File

@@ -0,0 +1,62 @@
package org.baeldung.java.sorting;
public class Employee implements Comparable {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public boolean equals(Object obj) {
return ((Employee) obj).getName()
.equals(getName());
}
@Override
public int compareTo(Object o) {
Employee e = (Employee) o;
return getName().compareTo(e.getName());
}
@Override
public String toString() {
return new StringBuffer().append("(")
.append(getName())
.append(getAge())
.append(",")
.append(getSalary())
.append(")")
.toString();
}
}

View File

@@ -0,0 +1,147 @@
package org.baeldung.java.sorting;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.Map.Entry;
import static org.junit.Assert.assertTrue;
public class JavaSortingUnitTest {
private int[] toSort;
private int[] sortedInts;
private int[] sortedRangeInts;
private Employee[] employees;
private Employee[] employeesSorted;
private Employee[] employeesSortedByAge;
private HashMap<Integer, String> map;
@Before
public void initVariables() {
toSort = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 };
sortedInts = new int[] { 1, 5, 7, 66, 88, 89, 123, 200, 255 };
sortedRangeInts = new int[] { 5, 1, 89, 7, 88, 200, 255, 123, 66 };
employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) };
employeesSorted = new Employee[] { new Employee("Earl", 43, 10000), new Employee("Frank", 33, 70000), new Employee("Jessica", 23, 4000), new Employee("John", 23, 5000), new Employee("Pearl", 33, 4000), new Employee("Steve", 26, 6000) };
employeesSortedByAge = new Employee[] { new Employee("John", 23, 5000), new Employee("Jessica", 23, 4000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 70000), new Employee("Pearl", 33, 4000), new Employee("Earl", 43, 10000) };
map = new HashMap<>();
map.put(55, "John");
map.put(22, "Apple");
map.put(66, "Earl");
map.put(77, "Pearl");
map.put(12, "George");
map.put(6, "Rocky");
}
@Test
public void givenIntArray_whenUsingSort_thenSortedArray() {
Arrays.sort(toSort);
assertTrue(Arrays.equals(toSort, sortedInts));
}
@Test
public void givenIntegerArray_whenUsingSort_thenSortedArray() {
Integer[] integers = ArrayUtils.toObject(toSort);
Arrays.sort(integers, Comparator.comparingInt(a -> a));
assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenArray_whenUsingSortWithLambdas_thenSortedArray() {
Integer[] integersToSort = ArrayUtils.toObject(toSort);
Arrays.sort(integersToSort, Comparator.comparingInt(a -> a));
assertTrue(Arrays.equals(integersToSort, ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() {
Arrays.sort(employees);
assertTrue(Arrays.equals(employees, employeesSorted));
}
@Test
public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() {
Arrays.sort(toSort, 3, 7);
assertTrue(Arrays.equals(toSort, sortedRangeInts));
}
@Test
public void givenIntArray_whenUsingParallelSort_thenArraySorted() {
Arrays.parallelSort(toSort);
assertTrue(Arrays.equals(toSort, sortedInts));
}
@Test
public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() {
List<Employee> employeesList = Arrays.asList(employees);
employeesList.sort(Comparator.comparing(Employee::getAge));// .thenComparing(Employee::getName));
assertTrue(Arrays.equals(employeesList.toArray(), employeesSortedByAge));
}
@Test
public void givenList_whenUsingSort_thenSortedList() {
List<Integer> toSortList = Ints.asList(toSort);
Collections.sort(toSortList);
assertTrue(Arrays.equals(toSortList.toArray(), ArrayUtils.toObject(sortedInts)));
}
@Test
public void givenMap_whenSortingByKeys_thenSortedMap() {
Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 };
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
entries.sort(Comparator.comparing(Entry::getKey));
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.keySet()
.toArray(), sortedKeys));
}
@Test
public void givenMap_whenSortingByValues_thenSortedMap() {
String[] sortedValues = new String[] { "Apple", "Earl", "George", "John", "Pearl", "Rocky" };
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
entries.sort(Comparator.comparing(Entry::getValue));
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.values()
.toArray(), sortedValues));
}
@Test
public void givenSet_whenUsingSort_thenSortedSet() {
HashSet<Integer> integersSet = new LinkedHashSet<>(Ints.asList(toSort));
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(255, 200, 123, 89, 88, 66, 7, 5, 1));
ArrayList<Integer> list = new ArrayList<>(integersSet);
list.sort((i1, i2) -> i2 - i1);
integersSet = new LinkedHashSet<>(list);
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
}
}