Merge branch 'master' into thombergs-patch-30

This commit is contained in:
Tom Hombergs
2018-10-02 20:40:07 +02:00
committed by GitHub
544 changed files with 11199 additions and 2670 deletions

View File

@@ -48,5 +48,7 @@
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [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)
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)

View File

@@ -63,6 +63,12 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
</dependencies>

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,96 @@
package com.baeldung.map.util;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
public class MapMax {
public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) {
Map.Entry<K, V> maxEntry = null;
for (Map.Entry<K, V> entry : map.entrySet()) {
if (maxEntry == null || entry.getValue()
.compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
return maxEntry.getValue();
}
public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() {
public int compare(Entry<K, V> e1, Entry<K, V> e2) {
return e1.getValue()
.compareTo(e2.getValue());
}
});
return maxEntry.getValue();
}
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue()));
return maxEntry.getValue();
}
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndMethodReference(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue));
return maxEntry.getValue();
}
public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream()
.max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue()));
return maxEntry.get()
.getValue();
}
public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue));
return maxEntry.get()
.getValue();
}
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 3);
map.put(2, 4);
map.put(3, 5);
map.put(4, 6);
map.put(5, 7);
MapMax mapMax = new MapMax();
System.out.println(mapMax.maxUsingIteration(map));
System.out.println(mapMax.maxUsingCollectionsMax(map));
System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map));
System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map));
System.out.println(mapMax.maxUsingStreamAndLambda(map));
System.out.println(mapMax.maxUsingStreamAndMethodReference(map));
}
}

View File

@@ -44,4 +44,12 @@ public class Employee {
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

View File

@@ -0,0 +1,60 @@
package com.baeldung.sort;
public class Employee implements Comparable<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 + '\'' +
'}';
}
@Override
public int compareTo(Employee employee) {
return (int)(this.id - employee.getId());
}
}

View File

@@ -0,0 +1,104 @@
package com.baeldung.sort;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import java.util.*;
import java.util.stream.Collectors;
public class SortHashMap {
private static Map<String, Employee> map = new HashMap<>();
public static void main(String[] args) {
initialize();
treeMapSortByKey();
arrayListSortByValue();
arrayListSortByKey();
sortStream();
sortGuava();
addDuplicates();
treeSetByKey();
treeSetByValue();
}
private static void sortGuava() {
final Ordering naturalOrdering =
Ordering.natural().onResultOf(Functions.forMap(map, null));
System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering));
}
private static void sortStream() {
map.entrySet().stream()
.sorted(Map.Entry.<String, Employee>comparingByKey().reversed())
.forEach(System.out::println);
Map<String, Employee> result = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
result.entrySet().forEach(System.out::println);
}
private static void treeSetByValue() {
SortedSet<Employee> values = new TreeSet<>(map.values());
System.out.println(values);
}
private static void treeSetByKey() {
SortedSet<String> keysSet = new TreeSet<>(map.keySet());
System.out.println(keysSet);
}
private static void treeMapSortByKey() {
TreeMap<String, Employee> sorted = new TreeMap<>(map);
sorted.putAll(map);
sorted.entrySet().forEach(System.out::println);
}
private static void arrayListSortByValue() {
List<Employee> employeeById = new ArrayList<>(map.values());
Collections.sort(employeeById);
System.out.println(employeeById);
}
private static void arrayListSortByKey() {
List<String> employeeByKey = new ArrayList<>(map.keySet());
Collections.sort(employeeByKey);
System.out.println(employeeByKey);
}
private static void initialize() {
Employee employee1 = new Employee(1L, "Mher");
map.put(employee1.getName(), employee1);
Employee employee2 = new Employee(22L, "Annie");
map.put(employee2.getName(), employee2);
Employee employee3 = new Employee(8L, "John");
map.put(employee3.getName(), employee3);
Employee employee4 = new Employee(2L, "George");
map.put(employee4.getName(), employee4);
}
private static void addDuplicates() {
Employee employee5 = new Employee(1L, "Mher");
map.put(employee5.getName(), employee5);
Employee employee6 = new Employee(22L, "Annie");
map.put(employee6.getName(), employee6);
}
}

View File

@@ -1,80 +0,0 @@
package com.baeldung.collection;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StreamOperateAndRemoveUnitTest {
private List<Item> itemList;
@Before
public void setup() {
itemList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
itemList.add(new Item(i));
}
}
@Test
public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
final List<Item> filteredList = itemList.stream().filter(item -> item.isQualified())
.collect(Collectors.toList());
Assert.assertEquals(5, filteredList.size());
}
@Test
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
final Predicate<Item> isQualified = item -> item.isQualified();
itemList.stream().filter(isQualified).forEach(item -> item.operate());
itemList.removeIf(isQualified);
Assert.assertEquals(5, itemList.size());
}
@Test
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
final List<Item> operatedList = new ArrayList<>();
itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
item.operate();
operatedList.add(item);
});
itemList.removeAll(operatedList);
Assert.assertEquals(5, itemList.size());
}
class Item {
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private final int value;
public Item(final int value) {
this.value = value;
}
public boolean isQualified() {
return value % 2 == 0;
}
public void operate() {
logger.info("Even Number: " + this.value);
}
}
}

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,59 @@
package com.baeldung.map.util;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class MapMaxUnitTest {
Map<Integer, Integer> map = null;
MapMax mapMax = null;
@Before
public void setupTestData() {
map = new HashMap<Integer, Integer>();
map.put(23, 12);
map.put(46, 24);
map.put(27, 38);
mapMax = new MapMax();
}
@Test
public void givenMap_whenIterated_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingIteration(map));
}
@Test
public void givenMap_whenUsingCollectionsMax_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMax(map));
}
@Test
public void givenMap_whenUsingCollectionsMaxAndLambda_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndLambda(map));
}
@Test
public void givenMap_whenUsingCollectionsMaxAndMethodReference_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndMethodReference(map));
}
@Test
public void givenMap_whenUsingStreamAndLambda_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingStreamAndLambda(map));
}
@Test
public void givenMap_whenUsingStreamAndMethodReference_thenReturnMaxValue() {
assertEquals(new Integer(38), mapMax.maxUsingStreamAndMethodReference (map));
}
}