JAVA-1188: Moved modules to core-java-modules

This commit is contained in:
sampadawagde
2020-04-07 14:50:03 +05:30
parent a3d01425f7
commit b0add81c74
39 changed files with 2959 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
## Java Collections Cookbooks and Examples
This module contains articles about Map data structures in Java.
### Relevant Articles:
- [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives)
- [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap)
- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap)
- [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap)
- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion)
- [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map)
- [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps)
- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort)
- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- More articles: [[<-- prev]](/core-java-collections-maps) [[next -->]](/core-java-collections-maps-3)

View File

@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-maps-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps-2</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.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collections.version}</version>
</dependency>
<dependency>
<groupId>net.sf.trove4j</groupId>
<artifactId>trove4j</artifactId>
<version>${trove4j.version}</version>
</dependency>
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>${fastutil.version}</version>
</dependency>
<dependency>
<groupId>colt</groupId>
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<streamex.version>0.6.5</streamex.version>
<commons-collections4.version>4.1</commons-collections4.version>
<avaitility.version>1.7.0</avaitility.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>

View File

@@ -0,0 +1,133 @@
package com.baeldung.map;
import java.util.*;
public class Product {
private String name;
private String description;
private List<String> tags;
public Product(String name, String description) {
this.name = name;
this.description = description;
this.tags = new ArrayList<>();
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public List<String> getTags() {
return tags;
}
public Product addTagsOfOtherProdcut(Product product) {
this.tags.addAll(product.getTags());
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Product product = (Product) o;
return Objects.equals(name, product.name) &&
Objects.equals(description, product.description);
}
@Override
public int hashCode() {
return Objects.hash(name, description);
}
public static void forEach() {
HashMap<String, Product> productsByName = new HashMap<>();
productsByName.forEach( (key, product)
-> System.out.println("Key: " + key + " Product:" + product.getDescription())
//do something with the key and value
);
//Prior to Java 8:
for(Map.Entry<String, Product> entry : productsByName.entrySet()) {
Product product = entry.getValue();
String key = entry.getKey();
//do something with the key and value
}
}
public static void getOrDefault() {
HashMap<String, Product> productsByName = new HashMap<>();
Product chocolate = new Product("chocolate", "something sweet");
Product defaultProduct = productsByName.getOrDefault("horse carriage", chocolate);
Product bike = productsByName.getOrDefault("E-Bike", chocolate);
//Prior to Java 8:
Product bike2 = productsByName.containsKey("E-Bike")
? productsByName.get("E-Bike")
: chocolate;
Product defaultProduct2 = productsByName.containsKey("horse carriage")
? productsByName.get("horse carriage")
: chocolate;
}
public static void putIfAbsent() {
HashMap<String, Product> productsByName = new HashMap<>();
Product chocolate = new Product("chocolate", "something sweet");
productsByName.putIfAbsent("E-Bike", chocolate);
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.put("E-Bike", chocolate);
}
}
public static void merge() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
eBike2.getTags().add("sport");
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProdcut);
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
}
public static void compute() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
productsByName.compute("E-Bike", (k,v) -> {
if(v != null) {
return v.addTagsOfOtherProdcut(eBike2);
} else {
return eBike2;
}
});
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.map.convert;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.stream.Collectors;
public class MapToString {
public static String convertWithIteration(Map<Integer, ?> map) {
StringBuilder mapAsString = new StringBuilder("{");
for (Integer key : map.keySet()) {
mapAsString.append(key + "=" + map.get(key) + ", ");
}
mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
return mapAsString.toString();
}
public static String convertWithStream(Map<Integer, ?> map) {
String mapAsString = map.keySet().stream()
.map(key -> key + "=" + map.get(key))
.collect(Collectors.joining(", ", "{", "}"));
return mapAsString;
}
public static String convertWithGuava(Map<Integer, ?> map) {
return Joiner.on(",").withKeyValueSeparator("=").join(map);
}
public static String convertWithApache(Map map) {
return StringUtils.join(map);
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.map.convert;
import com.google.common.base.Splitter;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class StringToMap {
public static Map<String, String> convertWithStream(String mapAsString) {
Map<String, String> map = Arrays.stream(mapAsString.split(","))
.map(entry -> entry.split("="))
.collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
return map;
}
public static Map<String, String> convertWithGuava(String mapAsString) {
return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString);
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.map.copyhashmap;
import org.apache.commons.lang3.SerializationUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
public class CopyHashMap {
public static <String, Employee> HashMap<String, Employee> copyUsingConstructor(HashMap<String, Employee> originalMap) {
return new HashMap<String, Employee>(originalMap);
}
public static <String, Employee> HashMap<String, Employee> copyUsingClone(HashMap<String, Employee> originalMap) {
return (HashMap<String, Employee>) originalMap.clone();
}
public static <String, Employee> HashMap<String, Employee> copyUsingPut(HashMap<String, Employee> originalMap) {
HashMap<String, Employee> shallowCopy = new HashMap<String, Employee>();
Set<Entry<String, Employee>> entries = originalMap.entrySet();
for(Map.Entry<String, Employee> mapEntry: entries) {
shallowCopy.put(mapEntry.getKey(), mapEntry.getValue());
}
return shallowCopy;
}
public static <String, Employee> HashMap<String, Employee> copyUsingPutAll(HashMap<String, Employee> originalMap) {
HashMap<String, Employee> shallowCopy = new HashMap<String, Employee>();
shallowCopy.putAll(originalMap);
return shallowCopy;
}
public static <String, Employee> HashMap<String, Employee> copyUsingJava8Stream(HashMap<String, Employee> originalMap) {
Set<Entry<String, Employee>> entries = originalMap.entrySet();
HashMap<String, Employee> shallowCopy = (HashMap<String, Employee>) entries
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return shallowCopy;
}
public static <String, Employee> HashMap<String, Employee> shallowCopy(HashMap<String, Employee> originalMap) {
return (HashMap<String, Employee>) originalMap.clone();
}
public static <String, Employee> HashMap<String, Employee> deepCopy(HashMap<String, Employee> originalMap) {
return SerializationUtils.clone(originalMap);
}
}

View File

@@ -0,0 +1,80 @@
package com.baeldung.map.initialize;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MapInitializer {
public static Map<String, String> articleMapOne;
static {
articleMapOne = new HashMap<>();
articleMapOne.put("ar01", "Intro to Map");
articleMapOne.put("ar02", "Some article");
}
public static Map<String, String> createSingletonMap() {
Map<String, String> passwordMap = Collections.singletonMap("username1", "password1");
return passwordMap;
}
public Map<String, String> createEmptyMap() {
Map<String, String> emptyMap = Collections.emptyMap();
return emptyMap;
}
public Map<String, String> createUsingDoubleBrace() {
Map<String, String> doubleBraceMap = new HashMap<String, String>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put("key1", "value1");
put("key2", "value2");
}
};
return doubleBraceMap;
}
public Map<String, String> createMapUsingStreamStringArray() {
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.toMap(data -> data[0], data -> data[1]));
return map;
}
public Map<String, Integer> createMapUsingStreamObjectArray() {
Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, })
.collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));
return map;
}
public Map<String, Integer> createMapUsingStreamSimpleEntry() {
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return map;
}
public Map<String, Integer> createMapUsingStreamSimpleImmutableEntry() {
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return map;
}
public Map<String, String> createImmutableMapWithStreams() {
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections::<String, String> unmodifiableMap));
return map;
}
}

View File

@@ -0,0 +1,74 @@
package com.baeldung.map.iteration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapIteration {
public static void main(String[] args) {
MapIteration mapIteration = new MapIteration();
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Three", 3);
map.put("Two", 2);
System.out.println("Iterating Keys of Map Using KeySet");
mapIteration.iterateKeys(map);
System.out.println("Iterating Map Using Entry Set");
mapIteration.iterateUsingEntrySet(map);
System.out.println("Iterating Using Iterator and Map Entry");
mapIteration.iterateUsingIteratorAndEntry(map);
System.out.println("Iterating Using KeySet and For Each");
mapIteration.iterateUsingKeySetAndForeach(map);
System.out.println("Iterating Map Using Lambda Expression");
mapIteration.iterateUsingLambda(map);
System.out.println("Iterating Using Stream API");
mapIteration.iterateUsingStreamAPI(map);
}
public void iterateUsingEntrySet(Map<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
public void iterateUsingLambda(Map<String, Integer> map) {
map.forEach((k, v) -> System.out.println((k + ":" + v)));
}
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> pair = iterator.next();
System.out.println(pair.getKey() + ":" + pair.getValue());
}
}
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
}
public void iterateUsingStreamAPI(Map<String, Integer> map) {
map.entrySet()
.stream()
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}
public void iterateKeys(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.println(key);
}
}
}

View File

@@ -0,0 +1,92 @@
package com.baeldung.map.mapmax;
import java.util.*;
import java.util.Map.Entry;
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

@@ -0,0 +1,60 @@
package com.baeldung.map.mergemaps;
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,105 @@
package com.baeldung.map.mergemaps;
import one.util.streamex.EntryStream;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MergeMaps {
private static Map<String, Employee> map1 = new HashMap<>();
private static Map<String, Employee> map2 = new HashMap<>();
public static void main(String[] args) {
initialize();
mergeFunction();
streamConcat();
streamOf();
streamEx();
streamMerge();
}
private static void streamMerge() {
Map<String, Employee> map3 = map2.entrySet()
.stream()
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> new Employee(v1.getId(), v2.getName()),
() -> new HashMap<>(map1)
)
);
System.out.println(map3);
}
private static void streamEx() {
Map<String, Employee> map3 = EntryStream.of(map1)
.append(EntryStream.of(map2))
.toMap((e1, e2) -> e1);
System.out.println(map3);
}
private static void streamOf() {
Map<String, Employee> map3 = Stream.of(map1, map2)
.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> new Employee(v1.getId(), v2.getName())
)
);
map3.entrySet().forEach(System.out::println);
}
private static void streamConcat() {
Map<String, Employee> result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(value1, value2) -> new Employee(value2.getId(), value1.getName())
));
result.entrySet().forEach(System.out::println);
}
private static void mergeFunction() {
Map<String, Employee> map3 = new HashMap<>(map1);
map2.forEach(
(key, value) -> map3.merge(key, value, (v1, v2) ->
new Employee(v1.getId(), v2.getName()))
);
map3.entrySet().forEach(System.out::println);
}
private static void initialize() {
Employee employee1 = new Employee(1L, "Henry");
map1.put(employee1.getName(), employee1);
Employee employee2 = new Employee(22L, "Annie");
map1.put(employee2.getName(), employee2);
Employee employee3 = new Employee(8L, "John");
map1.put(employee3.getName(), employee3);
Employee employee4 = new Employee(2L, "George");
map2.put(employee4.getName(), employee4);
Employee employee5 = new Employee(3L, "Henry");
map2.put(employee5.getName(), employee5);
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.map.primitives;
import cern.colt.map.AbstractIntDoubleMap;
import cern.colt.map.OpenIntDoubleHashMap;
import gnu.trove.map.TDoubleIntMap;
import gnu.trove.map.hash.TDoubleIntHashMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps;
import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap;
import org.eclipse.collections.api.map.primitive.MutableIntIntMap;
import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap;
import org.eclipse.collections.impl.factory.primitive.IntIntMaps;
import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps;
public class PrimitiveMaps {
public static void main(String[] args) {
eclipseCollectionsMap();
troveMap();
coltMap();
fastutilMap();
}
private static void fastutilMap() {
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap();
int2BooleanMap.put(1, true);
int2BooleanMap.put(7, false);
int2BooleanMap.put(4, true);
boolean value = int2BooleanMap.get(1);
Int2BooleanSortedMap int2BooleanSorted = Int2BooleanSortedMaps.EMPTY_MAP;
}
private static void coltMap() {
AbstractIntDoubleMap map = new OpenIntDoubleHashMap();
map.put(1, 4.5);
double value = map.get(1);
}
private static void eclipseCollectionsMap() {
MutableIntIntMap mutableIntIntMap = IntIntMaps.mutable.empty();
mutableIntIntMap.addToValue(1, 1);
ImmutableIntIntMap immutableIntIntMap = IntIntMaps.immutable.empty();
MutableObjectDoubleMap<String> dObject = ObjectDoubleMaps.mutable.empty();
dObject.addToValue("price", 150.5);
dObject.addToValue("quality", 4.4);
dObject.addToValue("stability", 0.8);
}
private static void troveMap() {
double[] doubles = new double[] {1.2, 4.5, 0.3};
int[] ints = new int[] {1, 4, 0};
TDoubleIntMap doubleIntMap = new TDoubleIntHashMap(doubles, ints);
doubleIntMap.put(1.2, 22);
doubleIntMap.put(4.5, 16);
doubleIntMap.adjustValue(1.2, 1);
doubleIntMap.adjustValue(4.5, 4);
doubleIntMap.adjustValue(0.3, 7);
}
}

View File

@@ -0,0 +1,104 @@
package com.baeldung.map.sort;
import com.baeldung.map.mergemaps.Employee;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableSortedMap;
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

@@ -0,0 +1,174 @@
package com.baeldung.map;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.*;
class ProductUnitTest {
@Test
public void getExistingValue() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike = new Product("E-Bike", "A bike with a battery");
Product roadBike = new Product("Road bike", "A bike for competition");
productsByName.put(eBike.getName(), eBike);
productsByName.put(roadBike.getName(), roadBike);
Product nextPurchase = productsByName.get("E-Bike");
assertEquals("A bike with a battery", nextPurchase.getDescription());
}
@Test
public void getNonExistingValue() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike = new Product("E-Bike", "A bike with a battery");
Product roadBike = new Product("Road bike", "A bike for competition");
productsByName.put(eBike.getName(), eBike);
productsByName.put(roadBike.getName(), roadBike);
Product nextPurchase = productsByName.get("Car");
assertNull(nextPurchase);
}
@Test
public void getExistingValueAfterSameKeyInsertedTwice() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike = new Product("E-Bike", "A bike with a battery");
Product roadBike = new Product("Road bike", "A bike for competition");
Product newEBike = new Product("E-Bike", "A bike with a better battery");
productsByName.put(eBike.getName(), eBike);
productsByName.put(roadBike.getName(), roadBike);
productsByName.put(newEBike.getName(), newEBike);
Product nextPurchase = productsByName.get("E-Bike");
assertEquals("A bike with a better battery", nextPurchase.getDescription());
}
@Test
public void getExistingValueWithNullKey() {
HashMap<String, Product> productsByName = new HashMap<>();
Product defaultProduct = new Product("Chocolate", "At least buy chocolate");
productsByName.put(null, defaultProduct);
productsByName.put(defaultProduct.getName(), defaultProduct);
Product nextPurchase = productsByName.get(null);
assertEquals("At least buy chocolate", nextPurchase.getDescription());
nextPurchase = productsByName.get("Chocolate");
assertEquals("At least buy chocolate", nextPurchase.getDescription());
}
@Test
public void insertSameObjectWithDifferentKey() {
HashMap<String, Product> productsByName = new HashMap<>();
Product defaultProduct = new Product("Chocolate", "At least buy chocolate");
productsByName.put(null, defaultProduct);
productsByName.put(defaultProduct.getName(), defaultProduct);
assertSame(productsByName.get(null), productsByName.get("Chocolate"));
}
@Test
public void checkIfKeyExists() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike = new Product("E-Bike", "A bike with a battery");
productsByName.put(eBike.getName(), eBike);
assertTrue(productsByName.containsKey("E-Bike"));
}
@Test
public void checkIfValueExists() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike = new Product("E-Bike", "A bike with a battery");
productsByName.put(eBike.getName(), eBike);
assertTrue(productsByName.containsValue(eBike));
}
@Test
public void removeExistingKey() {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike = new Product("E-Bike", "A bike with a battery");
Product roadBike = new Product("Road bike", "A bike for competition");
productsByName.put(eBike.getName(), eBike);
productsByName.put(roadBike.getName(), roadBike);
productsByName.remove("E-Bike");
assertNull(productsByName.get("E-Bike"));
}
@Test
public void givenMutableKeyWhenKeyChangeThenValueNotFound() {
// Given
MutableKey key = new MutableKey("initial");
Map<MutableKey, String> items = new HashMap<>();
items.put(key, "success");
// When
key.setName("changed");
// Then
assertNull(items.get(key));
}
static class MutableKey {
private String name;
public MutableKey(String name) {
this.name = name;
}
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;
}
MutableKey that = (MutableKey) o;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.map.convert;
import org.apache.commons.collections4.MapUtils;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
public class MapToStringUnitTest {
private Map<Integer, String> wordsByKey = new HashMap<>();
@BeforeEach
public void setup() {
wordsByKey.clear();
wordsByKey.put(1, "one");
wordsByKey.put(2, "two");
wordsByKey.put(3, "three");
wordsByKey.put(4, "four");
}
@Test
public void givenMap_WhenUsingIteration_ThenResultingMapIsCorrect() {
String mapAsString = MapToString.convertWithIteration(wordsByKey);
Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString);
}
@Test
public void givenMap_WhenUsingStream_ThenResultingMapIsCorrect() {
String mapAsString = MapToString.convertWithStream(wordsByKey);
Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString);
}
@Test
public void givenMap_WhenUsingGuava_ThenResultingMapIsCorrect() {
String mapAsString = MapToString.convertWithGuava(wordsByKey);
Assert.assertEquals("1=one,2=two,3=three,4=four", mapAsString);
}
@Test
public void givenMap_WhenUsingApache_ThenResultingMapIsCorrect() {
String mapAsString = MapToString.convertWithApache(wordsByKey);
Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString);
MapUtils.debugPrint(System.out, "Map as String", wordsByKey);
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.map.convert;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import java.util.Map;
public class StringToMapUnitTest {
@Test
public void givenString_WhenUsingStream_ThenResultingStringIsCorrect() {
Map<String, String> wordsByKey = StringToMap.convertWithStream("1=one,2=two,3=three,4=four");
Assert.assertEquals(4, wordsByKey.size());
Assert.assertEquals("one", wordsByKey.get("1"));
}
@Test
void givenString_WhenUsingGuava_ThenResultingStringIsCorrect() {
Map<String, String> wordsByKey = StringToMap.convertWithGuava("1=one,2=two,3=three,4=four");
Assert.assertEquals(4, wordsByKey.size());
Assert.assertEquals("one", wordsByKey.get("1"));
}
}

View File

@@ -0,0 +1,76 @@
package com.baeldung.map.copyhashmap;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class CopyHashMapUnitTest {
@Test
public void givenHashMap_whenShallowCopy_thenCopyisNotSameAsOriginal() {
HashMap<String, Employee> map = new HashMap<>();
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Norman");
map.put("emp1",emp1);
map.put("emp2",emp2);
HashMap<String, Employee> shallowCopy = CopyHashMap.shallowCopy(map);
assertThat(shallowCopy).isNotSameAs(map);
}
@Test
public void givenHashMap_whenShallowCopyModifyingOriginalObject_thenCopyShouldChange() {
HashMap<String, Employee> map = new HashMap<>();
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Norman");
map.put("emp1",emp1);
map.put("emp2",emp2);
HashMap<String, Employee> shallowCopy = CopyHashMap.shallowCopy(map);
emp1.setName("Johny");
assertThat(shallowCopy.get("emp1")).isEqualTo(map.get("emp1"));
}
@Test
public void givenHashMap_whenDeepCopyModifyingOriginalObject_thenCopyShouldNotChange() {
HashMap<String, Employee> map = new HashMap<>();
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Norman");
map.put("emp1",emp1);
map.put("emp2",emp2);
HashMap<String, Employee> deepCopy = CopyHashMap.deepCopy(map);
emp1.setName("Johny");
assertThat(deepCopy.get("emp1")).isNotEqualTo(map.get("emp1"));
}
@Test
public void givenImmutableMap_whenCopyUsingGuava_thenCopyShouldNotChange() {
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Norman");
Map<String, Employee> map = ImmutableMap.<String, Employee> builder()
.put("emp1",emp1)
.put("emp2",emp2)
.build();
Map<String, Employee> shallowCopy = ImmutableMap.copyOf(map);
assertThat(shallowCopy).isSameAs(map);
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.map.copyhashmap;
import java.io.Serializable;
public class Employee implements Serializable{
private String name;
public Employee(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.map.initialize;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class MapInitializerUnitTest {
@Test
public void givenStaticMap_whenUpdated_thenCorrect() {
MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List");
assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List");
}
@Test(expected=UnsupportedOperationException.class)
public void givenSingleTonMap_whenEntriesAdded_throwsException() {
Map<String, String> map = MapInitializer.createSingletonMap();
map.put("username2", "password2");
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.map.mapmax;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
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));
}
}

View File

@@ -0,0 +1,72 @@
package com.baeldung.map.weakhashmap;
import org.junit.Test;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static org.junit.Assert.assertTrue;
public class WeakHashMapUnitTest {
@Test
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() {
//given
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
BigImage bigImage = new BigImage("image_id");
UniqueImageName imageName = new UniqueImageName("name_of_big_image");
map.put(imageName, bigImage);
assertTrue(map.containsKey(imageName));
//when big image key is not reference anywhere
imageName = null;
System.gc();
//then GC will finally reclaim that object
await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty);
}
@Test
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() {
//given
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
BigImage bigImageFirst = new BigImage("foo");
UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image");
BigImage bigImageSecond = new BigImage("foo_2");
UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2");
map.put(imageNameFirst, bigImageFirst);
map.put(imageNameSecond, bigImageSecond);
assertTrue(map.containsKey(imageNameFirst));
assertTrue(map.containsKey(imageNameSecond));
//when
imageNameFirst = null;
System.gc();
//then
await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1);
await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond));
}
class BigImage {
public final String imageId;
BigImage(String imageId) {
this.imageId = imageId;
}
}
class UniqueImageName {
public final String imageName;
UniqueImageName(String imageName) {
this.imageName = imageName;
}
}
}