Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-3860

This commit is contained in:
mthomas
2020-04-14 06:44:48 -05:00
491 changed files with 9408 additions and 2307 deletions

View File

@@ -7,3 +7,4 @@ This module contains articles about Java 14.
- [Guide to the @Serial Annotation in Java 14](https://www.baeldung.com/java-14-serial-annotation)
- [Java Text Blocks](https://www.baeldung.com/java-text-blocks)
- [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof)
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)

View File

@@ -0,0 +1,56 @@
package com.baeldung.java14.helpfulnullpointerexceptions;
public class HelpfulNullPointerException {
public static void main(String[] args) {
Employee employee = null;
employee.getName();
}
public String getEmployeeEmailAddress(Employee employee) {
String emailAddress = employee.getPersonalDetails().getEmailAddress().toLowerCase();
return emailAddress;
}
static class Employee {
String name;
PersonalDetails personalDetails;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PersonalDetails getPersonalDetails() {
return personalDetails;
}
public void setPersonalDetails(PersonalDetails personalDetails) {
this.personalDetails = personalDetails;
}
}
static class PersonalDetails {
String emailAddress;
String phone;
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.java14.helpfulnullpointerexceptions;
import org.junit.Test;
import static com.baeldung.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.Employee;
import static com.baeldung.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.PersonalDetails;
import static org.assertj.core.api.Assertions.assertThat;
public class HelpfulNullPointerExceptionUnitTest {
@Test (expected = NullPointerException.class)
public void givenAnEmptyPersonalDetails_whenEmailAddressIsAccessed_thenThrowNPE() {
var helpfulNPE = new HelpfulNullPointerException();
var employee = new Employee();
employee.setName("Eduard");
employee.setPersonalDetails(new PersonalDetails());
helpfulNPE.getEmployeeEmailAddress(employee);
}
@Test
public void givenCompletePersonalDetails_whenEmailAddressIsAccessed_thenSuccess() {
var helpfulNPE = new HelpfulNullPointerException();
var emailAddress = "eduard@gmx.com";
var employee = new Employee();
employee.setName("Eduard");
var personalDetails = new PersonalDetails();
personalDetails.setEmailAddress(emailAddress.toUpperCase());
personalDetails.setPhone("1234");
employee.setPersonalDetails(personalDetails);
assertThat(helpfulNPE.getEmployeeEmailAddress(employee)).isEqualTo(emailAddress);
}
}

View File

@@ -4,7 +4,6 @@ This module contains articles about Java 8 core features
### Relevant Articles:
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
- [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments)
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)

View File

@@ -8,5 +8,4 @@ This module contains articles about Java 9 core features
- [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue)
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list)

View File

@@ -12,4 +12,3 @@
- [Sorting in Java](https://www.baeldung.com/java-sorting)
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)

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-modules/core-java-collections-maps) [[next -->]](/core-java-modules/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;
}
}
}

View File

@@ -0,0 +1,8 @@
## Java Collections Cookbooks and Examples
This module contains articles about Map data structures in Java.
### Relevant Articles:
- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap)
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)

View File

@@ -0,0 +1,26 @@
<?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-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps-3</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>
</dependencies>
<properties>
</properties>
</project>

View File

@@ -0,0 +1,225 @@
package com.baeldung.map.compare;
import com.google.common.base.Equivalence;
import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapContaining.hasKey;
import static org.junit.Assert.*;
public class HashMapComparisonUnitTest {
Map<String, String> asiaCapital1;
Map<String, String> asiaCapital2;
Map<String, String> asiaCapital3;
Map<String, String[]> asiaCity1;
Map<String, String[]> asiaCity2;
Map<String, String[]> asiaCity3;
@Before
public void setup(){
asiaCapital1 = new HashMap<String, String>();
asiaCapital1.put("Japan", "Tokyo");
asiaCapital1.put("South Korea", "Seoul");
asiaCapital2 = new HashMap<String, String>();
asiaCapital2.put("South Korea", "Seoul");
asiaCapital2.put("Japan", "Tokyo");
asiaCapital3 = new HashMap<String, String>();
asiaCapital3.put("Japan", "Tokyo");
asiaCapital3.put("China", "Beijing");
asiaCity1 = new HashMap<String, String[]>();
asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" });
asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" });
asiaCity2 = new HashMap<String, String[]>();
asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" });
asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" });
asiaCity3 = new HashMap<String, String[]>();
asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" });
asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" });
}
@Test
public void whenCompareTwoHashMapsUsingEquals_thenSuccess() {
assertTrue(asiaCapital1.equals(asiaCapital2));
assertFalse(asiaCapital1.equals(asiaCapital3));
}
@Test
public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() {
assertFalse(asiaCity1.equals(asiaCity2));
}
@Test
public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() {
assertTrue(areEqual(asiaCapital1, asiaCapital2));
assertFalse(areEqual(asiaCapital1, asiaCapital3));
}
@Test
public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() {
assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2));
assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3));
}
@Test
public void whenCompareTwoHashMapKeys_thenSuccess() {
assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet()));
assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet()));
}
@Test
public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() {
Map<String, String> asiaCapital3 = new HashMap<String, String>();
asiaCapital3.put("Japan", "Tokyo");
asiaCapital3.put("South Korea", "Seoul");
asiaCapital3.put("China", "Beijing");
Map<String, String> asiaCapital4 = new HashMap<String, String>();
asiaCapital4.put("South Korea", "Seoul");
asiaCapital4.put("Japan", "Osaka");
asiaCapital4.put("China", "Beijing");
Map<String, Boolean> result = areEqualKeyValues(asiaCapital3, asiaCapital4);
assertEquals(3, result.size());
assertThat(result, hasEntry("Japan", false));
assertThat(result, hasEntry("South Korea", true));
assertThat(result, hasEntry("China", true));
}
@Test
public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() {
Map<String, String> asia1 = new HashMap<String, String>();
asia1.put("Japan", "Tokyo");
asia1.put("South Korea", "Seoul");
asia1.put("India", "New Delhi");
Map<String, String> asia2 = new HashMap<String, String>();
asia2.put("Japan", "Tokyo");
asia2.put("China", "Beijing");
asia2.put("India", "Delhi");
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
Map<String, ValueDifference<String>> entriesDiffering = diff.entriesDiffering();
assertFalse(diff.areEqual());
assertEquals(1, entriesDiffering.size());
assertThat(entriesDiffering, hasKey("India"));
assertEquals("New Delhi", entriesDiffering.get("India").leftValue());
assertEquals("Delhi", entriesDiffering.get("India").rightValue());
}
@Test
public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() {
Map<String, String> asia1 = new HashMap<String, String>();
asia1.put("Japan", "Tokyo");
asia1.put("South Korea", "Seoul");
asia1.put("India", "New Delhi");
Map<String, String> asia2 = new HashMap<String, String>();
asia2.put("Japan", "Tokyo");
asia2.put("China", "Beijing");
asia2.put("India", "Delhi");
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
Map<String, String> entriesOnlyOnRight = diff.entriesOnlyOnRight();
Map<String, String> entriesOnlyOnLeft = diff.entriesOnlyOnLeft();
assertEquals(1, entriesOnlyOnRight.size());
assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing"));
assertEquals(1, entriesOnlyOnLeft.size());
assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul"));
}
@Test
public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() {
Map<String, String> asia1 = new HashMap<String, String>();
asia1.put("Japan", "Tokyo");
asia1.put("South Korea", "Seoul");
asia1.put("India", "New Delhi");
Map<String, String> asia2 = new HashMap<String, String>();
asia2.put("Japan", "Tokyo");
asia2.put("China", "Beijing");
asia2.put("India", "Delhi");
MapDifference<String, String> diff = Maps.difference(asia1, asia2);
Map<String, String> entriesInCommon = diff.entriesInCommon();
assertEquals(1, entriesInCommon.size());
assertThat(entriesInCommon, hasEntry("Japan", "Tokyo"));
}
@Test
public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() {
MapDifference<String, String[]> diff = Maps.difference(asiaCity1, asiaCity2);
assertFalse(diff.areEqual());
}
@Test
public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() {
Equivalence<String[]> eq = new Equivalence<String[]>() {
@Override
protected boolean doEquivalent(String[] a, String[] b) {
return Arrays.equals(a, b);
}
@Override
protected int doHash(String[] value) {
return value.hashCode();
}
};
MapDifference<String, String[]> diff = Maps.difference(asiaCity1, asiaCity2, eq);
assertTrue(diff.areEqual());
diff = Maps.difference(asiaCity1, asiaCity3, eq);
assertFalse(diff.areEqual());
}
// ===========================================================================
private boolean areEqual(Map<String, String> first, Map<String, String> second) {
if (first.size() != second.size()) {
return false;
}
return first.entrySet()
.stream()
.allMatch(e -> e.getValue()
.equals(second.get(e.getKey())));
}
private boolean areEqualWithArrayValue(Map<String, String[]> first, Map<String, String[]> second) {
if (first.size() != second.size()) {
return false;
}
return first.entrySet()
.stream()
.allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey())));
}
private Map<String, Boolean> areEqualKeyValues(Map<String, String> first, Map<String, String> second) {
return first.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey()))));
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.map.treemaphashmap;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapVsHashMapUnitTest {
@Test
public void whenInsertObjectsTreeMap_thenNaturalOrder() {
Map<Integer, String> treemap = new TreeMap<>();
treemap.put(3, "TreeMap");
treemap.put(2, "vs");
treemap.put(1, "HashMap");
Assert.assertThat(treemap.keySet(), Matchers.contains(1, 2, 3));
}
@Test(expected = NullPointerException.class)
public void whenInsertNullInTreeMap_thenException() {
Map<Integer, String> treemap = new TreeMap<>();
treemap.put(null, "NullPointerException");
}
@Test
public void whenInsertObjectsHashMap_thenRandomOrder() {
Map<Integer, String> hashmap = new HashMap<>();
hashmap.put(3, "TreeMap");
hashmap.put(2, "vs");
hashmap.put(1, "HashMap");
Assert.assertThat(hashmap.keySet(), Matchers.containsInAnyOrder(1, 2, 3));
}
@Test
public void whenInsertNullInHashMap_thenInsertsNull() {
Map<Integer, String> hashmap = new HashMap<>();
hashmap.put(null, null);
Assert.assertNull(hashmap.get(null));
}
@Test
public void givenHashMapAndTreeMap_whenputDuplicates_thenOnlyUnique() {
Map<Integer, String> treeMap = new HashMap<>();
treeMap.put(1, "Baeldung");
treeMap.put(1, "Baeldung");
Assert.assertTrue(treeMap.size() == 1);
Map<Integer, String> treeMap2 = new TreeMap<>();
treeMap2.put(1, "Baeldung");
treeMap2.put(1, "Baeldung");
Assert.assertTrue(treeMap2.size() == 1);
}
}

View File

@@ -0,0 +1,15 @@
## Java Collections Cookbooks and Examples
This module contains articles about Map data structures in Java.
### Relevant Articles:
- [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap)
- [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap)
- [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap)
- [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys)
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
- [How to Check If a Key Exists in a Map](https://www.baeldung.com/java-map-key-exists)
- [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps)
- [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map)
- [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap-advanced)
- More articles: [[next -->]](/core-java-modules/core-java-collections-maps-2)

View File

@@ -0,0 +1,35 @@
<?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</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps</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.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@@ -0,0 +1,44 @@
/**
*
*/
package com.baeldung.map;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Stream;
/**
* @author swpraman
*
*/
public class MapUtil {
public static <K, V> Stream<K> keys(Map<K, V> map, V value) {
return map.entrySet()
.stream()
.filter(entry -> value.equals(entry.getValue()))
.map(Map.Entry::getKey);
}
public static <K, V> Set<K> getKeys(Map<K, V> map, V value) {
Set<K> keys = new HashSet<>();
for (Entry<K, V> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
keys.add(entry.getKey());
}
}
return keys;
}
public static <K, V> K getKey(Map<K, V> map, V value) {
for (Entry<K, V> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
}

View File

@@ -0,0 +1,64 @@
package com.baeldung.map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyKey {
private static final Logger LOG = LoggerFactory.getLogger(MyKey.class);
private String name;
private int id;
public MyKey(int id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
LOG.debug("Calling hashCode()");
return id;
}
@Override
public String toString() {
return "MyKey [name=" + name + ", id=" + id + "]";
}
@Override
public boolean equals(Object obj) {
LOG.debug("Calling equals() for key: " + obj);
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyKey other = (MyKey) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.map;
import java.util.LinkedHashMap;
import java.util.Map;
public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int MAX_ENTRIES = 5;
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor, accessOrder);
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
}

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,120 @@
package com.baeldung.guava;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.google.common.collect.BiMap;
import com.google.common.collect.EnumHashBiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
public class GuavaBiMapUnitTest {
@Test
public void whenQueryByValue_returnsKey() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
final String countryCapitalName = capitalCountryBiMap.inverse().get("India");
assertEquals("New Delhi", countryCapitalName);
}
@Test
public void whenCreateBiMapFromExistingMap_returnsKey() {
final Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("New Delhi", "India");
capitalCountryMap.put("Washingon, D.C.", "USA");
capitalCountryMap.put("Moscow", "Russia");
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create(capitalCountryMap);
final String countryCapitalName = capitalCountryBiMap.inverse().get("India");
assertEquals("New Delhi", countryCapitalName);
}
@Test
public void whenQueryByKey_returnsValue() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test(expected = IllegalArgumentException.class)
public void whenSameValueIsPresent_throwsException() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.put("Trump", "USA");
}
@Test
public void givenSameValueIsPresent_whenForcePut_completesSuccessfully() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.forcePut("Trump", "USA");
assertEquals("USA", capitalCountryBiMap.get("Trump"));
assertEquals("Trump", capitalCountryBiMap.inverse().get("USA"));
}
@Test
public void whenSameKeyIsPresent_replacesAlreadyPresent() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.put("Washingon, D.C.", "HongKong");
assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test
public void whenUsingImmutableBiMap_allowsPutSuccessfully() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test(expected = UnsupportedOperationException.class)
public void whenUsingImmutableBiMap_doesntAllowRemove() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
capitalCountryBiMap.remove("New Delhi");
}
@Test(expected = UnsupportedOperationException.class)
public void whenUsingImmutableBiMap_doesntAllowPut() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
capitalCountryBiMap.put("New York", "USA");
}
private enum Operation {
ADD, SUBTRACT, MULTIPLY, DIVIDE
}
@Test
public void whenUsingEnumAsKeyInMap_replacesAlreadyPresent() {
final BiMap<Operation, String> operationStringBiMap = EnumHashBiMap.create(Operation.class);
operationStringBiMap.put(Operation.ADD, "Add");
operationStringBiMap.put(Operation.SUBTRACT, "Subtract");
operationStringBiMap.put(Operation.MULTIPLY, "Multiply");
operationStringBiMap.put(Operation.DIVIDE, "Divide");
assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE));
}
}

View File

@@ -0,0 +1,84 @@
package com.baeldung.map;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
public class ImmutableMapUnitTest {
@Test
public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(mutableMap);
assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertFalse(unmodifiableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertTrue(unmodifiableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(mutableMap);
assertTrue(immutableMap.containsKey("USA"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertTrue(immutableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertFalse(immutableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
ImmutableMap<String, String> immutableMap = ImmutableMap.<String, String>builder()
.putAll(mutableMap)
.put("Costa Rica", "North America")
.build();
assertTrue(immutableMap.containsKey("USA"));
assertTrue(immutableMap.containsKey("Costa Rica"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertTrue(immutableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertFalse(immutableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
ImmutableMap<String, String> immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
assertTrue(immutableMap.containsKey("USA"));
assertTrue(immutableMap.containsKey("Costa Rica"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.map;
import org.junit.Test;
import java.util.Collections;
import java.util.Map;
import static org.junit.Assert.*;
public class KeyCheckUnitTest {
@Test
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
Map<String, String> map = Collections.singletonMap("key", "value");
assertTrue(map.containsKey("key"));
assertFalse(map.containsKey("missing"));
}
@Test
public void whenKeyHasNullValue_thenGetStillWorks() {
Map<String, String> map = Collections.singletonMap("nothing", null);
assertTrue(map.containsKey("nothing"));
assertNull(map.get("nothing"));
}
}

View File

@@ -0,0 +1,119 @@
package com.baeldung.map;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.apache.commons.collections4.MultiMap;
import org.apache.commons.collections4.MultiMapUtils;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.map.MultiValueMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MapMultipleValuesUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesUnitTest.class);
@Test
public void givenHashMap_whenPuttingTwice_thenReturningFirstValue() {
Map<String, String> map = new HashMap<>();
assertThat(map.put("key1", "value1")).isEqualTo(null);
assertThat(map.put("key1", "value2")).isEqualTo("value1");
assertThat(map.get("key1")).isEqualTo("value2");
}
@Test
public void givenCollectionAsValue_whenPuttingTwice_thenReturningCollection() {
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
map.put("key1", list);
map.get("key1").add("value1");
map.get("key1").add("value2");
assertThat(map.get("key1").get(0)).isEqualTo("value1");
assertThat(map.get("key1").get(1)).isEqualTo("value2");
}
@Test
public void givenCollectionAsValueAndJava8_whenPuttingTwice_thenReturningCollection() {
Map<String, List<String>> map = new HashMap<>();
map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1");
map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2");
assertThat(map.get("key1").get(0)).isEqualTo("value1");
assertThat(map.get("key1").get(1)).isEqualTo("value2");
}
@Test
public void givenMultiValueMap_whenPuttingTwice_thenReturningValues() {
MultiMap<String, String> map = new MultiValueMap<>();
map.put("key1", "value1");
map.put("key1", "value2");
assertThat((Collection<String>) map.get("key1"))
.contains("value1", "value2");
}
@Test
public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key1", "value1");
map.put("key1", "value2");
map.put("key1", "value2");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value1", "value2", "value2");
}
@Test
public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() {
MultiValuedMap<String, String> map = new HashSetValuedHashMap<>();
map.put("key1", "value1");
map.put("key1", "value1");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value1");
}
@Test(expected = UnsupportedOperationException.class)
public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key1", "value1");
map.put("key1", "value2");
MultiValuedMap<String, String> immutableMap =
MultiMapUtils.unmodifiableMultiValuedMap(map);
immutableMap.put("key1", "value3");
}
@Test
public void givenArrayListMultiMap_whenInserting_thenCorrectOutput() {
Multimap<String, String> map = ArrayListMultimap.create();
map.put("key1", "value2");
map.put("key1", "value1");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value2", "value1");
}
@Test
public void givenLinkedHashMultiMap_whenInserting_thenReturningValuesInInsertionOrder() {
Multimap<String, String> map = LinkedHashMultimap.create();
map.put("key1", "value3");
map.put("key1", "value1");
map.put("key1", "value2");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value3", "value1", "value2");
}
@Test
public void givenTreeMultimap_whenInserting_thenReturningValuesInNaturalOrder() {
Multimap<String, String> map = TreeMultimap.create();
map.put("key1", "value3");
map.put("key1", "value1");
map.put("key1", "value2");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value1", "value2", "value3");
}
}

View File

@@ -0,0 +1,336 @@
package com.baeldung.map;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.Map.Entry;
import static org.junit.Assert.*;
public class MapUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(MapUnitTest.class);
@Test
public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Set<String> keys = map.keySet();
assertEquals(2, keys.size());
assertTrue(keys.contains("name"));
assertTrue(keys.contains("type"));
}
@Test
public void givenHashMap_whenRetrievesValues_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Collection<String> values = map.values();
assertEquals(2, values.size());
assertTrue(values.contains("baeldung"));
assertTrue(values.contains("blog"));
}
@Test
public void givenHashMap_whenRetrievesEntries_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Set<Entry<String, String>> entries = map.entrySet();
assertEquals(2, entries.size());
for (Entry<String, String> e : entries) {
String key = e.getKey();
String val = e.getValue();
assertTrue(key.equals("name") || key.equals("type"));
assertTrue(val.equals("baeldung") || val.equals("blog"));
}
}
@Test
public void givenKeySet_whenChangeReflectsInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
assertEquals(2, map.size());
Set<String> keys = map.keySet();
keys.remove("name");
assertEquals(1, map.size());
}
@Test(expected = ConcurrentModificationException.class)
public void givenIterator_whenFailsFastOnModification_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
map.remove("type");
while (it.hasNext()) {
String key = it.next();
}
}
public void givenIterator_whenRemoveWorks_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
assertEquals(0, map.size());
}
@Test
public void whenHashCodeIsCalledOnPut_thenCorrect() {
MyKey key = new MyKey(1, "name");
Map<MyKey, String> map = new HashMap<>();
map.put(key, "val");
}
@Test
public void whenHashCodeIsCalledOnGet_thenCorrect() {
MyKey key = new MyKey(1, "name");
Map<MyKey, String> map = new HashMap<>();
map.put(key, "val");
map.get(key);
}
@Test
public void whenGetWorks_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key", "val");
String val = map.get("key");
assertEquals("val", val);
}
@Test
public void givenNewKey_whenPutReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();
String rtnVal = map.put("key1", "val1");
assertNull(rtnVal);
}
@Test
public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();
String rtnVal = map.get("key1");
assertNull(rtnVal);
}
@Test
public void givenNullVal_whenPutReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();
String rtnVal = map.put("key1", null);
assertNull(rtnVal);
}
@Test
public void givenNullKeyAndVal_whenAccepts_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put(null, null);
}
@Test
public void givenNullVal_whenRetrieves_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key", null);
String val = map.get("key");
assertNull(val);
}
@Test
public void whenContainsDistinguishesNullValues_thenCorrect() {
Map<String, String> map = new HashMap<>();
String val1 = map.get("key");
boolean valPresent = map.containsKey("key");
assertNull(val1);
assertFalse(valPresent);
map.put("key", null);
String val = map.get("key");
valPresent = map.containsKey("key");
assertNull(val);
assertTrue(valPresent);
}
@Test
public void whenPutReturnsPrevValue_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key1", "val1");
String rtnVal = map.put("key1", "val2");
assertEquals("val1", rtnVal);
}
@Test
public void whenCallsEqualsOnCollision_thenCorrect() {
HashMap<MyKey, String> map = new HashMap<>();
MyKey k1 = new MyKey(1, "firstKey");
MyKey k2 = new MyKey(2, "secondKey");
MyKey k3 = new MyKey(2, "thirdKey");
LOG.debug("storing value for k1");
map.put(k1, "firstValue");
LOG.debug("storing value for k2");
map.put(k2, "secondValue");
LOG.debug("storing value for k3");
map.put(k3, "thirdValue");
LOG.debug("retrieving value for k1");
String v1 = map.get(k1);
LOG.debug("retrieving value for k2");
String v2 = map.get(k2);
LOG.debug("retrieving value for k3");
String v3 = map.get(k3);
assertEquals("firstValue", v1);
assertEquals("secondValue", v2);
assertEquals("thirdValue", v3);
}
@Test
public void givenLinkedHashMap_whenGetsOrderedKeyset_thenCorrect() {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, null);
map.put(2, null);
map.put(3, null);
map.put(4, null);
map.put(5, null);
Set<Integer> keys = map.keySet();
Integer[] arr = keys.toArray(new Integer[0]);
for (int i = 0; i < arr.length; i++) {
assertEquals(new Integer(i + 1), arr[i]);
}
}
@Test
public void givenLinkedHashMap_whenAccessOrderWorks_thenCorrect() {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, .75f, true);
map.put(1, null);
map.put(2, null);
map.put(3, null);
map.put(4, null);
map.put(5, null);
Set<Integer> keys = map.keySet();
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
map.get(4);
assertEquals("[1, 2, 3, 5, 4]", keys.toString());
map.get(1);
assertEquals("[2, 3, 5, 4, 1]", keys.toString());
map.get(3);
assertEquals("[2, 5, 4, 1, 3]", keys.toString());
}
@Test
public void givenLinkedHashMap_whenRemovesEldestEntry_thenCorrect() {
LinkedHashMap<Integer, String> map = new MyLinkedHashMap<>(16, .75f, true);
map.put(1, null);
map.put(2, null);
map.put(3, null);
map.put(4, null);
map.put(5, null);
Set<Integer> keys = map.keySet();
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
map.put(6, null);
assertEquals("[2, 3, 4, 5, 6]", keys.toString());
map.put(7, null);
assertEquals("[3, 4, 5, 6, 7]", keys.toString());
map.put(8, null);
assertEquals("[4, 5, 6, 7, 8]", keys.toString());
}
@Test
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect() {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "val");
map.put(2, "val");
map.put(1, "val");
map.put(5, "val");
map.put(4, "val");
assertEquals("[1, 2, 3, 4, 5]", map.keySet().toString());
}
@Test
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect2() {
TreeMap<String, String> map = new TreeMap<>();
map.put("c", "val");
map.put("b", "val");
map.put("a", "val");
map.put("e", "val");
map.put("d", "val");
assertEquals("[a, b, c, d, e]", map.keySet().toString());
}
@Test
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder());
map.put(3, "val");
map.put(2, "val");
map.put(1, "val");
map.put(5, "val");
map.put(4, "val");
assertEquals("[5, 4, 3, 2, 1]", map.keySet().toString());
}
@Test
public void givenTreeMap_whenPerformsQueries_thenCorrect() {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "val");
map.put(2, "val");
map.put(1, "val");
map.put(5, "val");
map.put(4, "val");
Integer highestKey = map.lastKey();
Integer lowestKey = map.firstKey();
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
Set<Integer> keysGreaterThanEqTo3 = map.tailMap(3).keySet();
assertEquals(new Integer(5), highestKey);
assertEquals(new Integer(1), lowestKey);
assertEquals("[1, 2]", keysLessThan3.toString());
assertEquals("[3, 4, 5]", keysGreaterThanEqTo3.toString());
}
}

View File

@@ -0,0 +1,103 @@
/**
*
*/
package com.baeldung.map;
import com.google.common.collect.HashBiMap;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
/**
* @author swpraman
*
*/
public class MapUtilUnitTest {
@Test
public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() {
Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("Tokyo", "Japan");
capitalCountryMap.put("New Delhi", "India");
assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India"));
}
@Test
public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() {
Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("Tokyo", "Japan");
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
capitalCountryMap.put("Bloemfontein", "South Africa");
assertEquals(new HashSet<String>(Arrays.asList(
new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),
MapUtil.getKeys(capitalCountryMap, "South Africa"));
}
@Test
public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() {
Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("Tokyo", "Japan");
capitalCountryMap.put("Berlin", "Germany");
assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get());
}
@Test
public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() {
Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("Tokyo", "Japan");
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
capitalCountryMap.put("Bloemfontein", "South Africa");
assertEquals(new HashSet<String>(Arrays.asList(
new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),
MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet()));
}
@Test
public void whenUsingBidiMap_shouldReturnKey() {
BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
assertEquals("Berlin", capitalCountryMap.getKey("Germany"));
}
@Test
public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() {
BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
assertEquals("Pretoria", capitalCountryMap.getKey("South Africa"));
}
@Test
public void whenUsingBiMap_shouldReturnKey() {
HashBiMap<String, String> capitalCountryMap = HashBiMap.create();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
assertEquals("Berlin", capitalCountryMap.inverse().get("Germany"));
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingBiMapAddDuplicateValue_shouldThrowException() {
HashBiMap<String, String> capitalCountryMap = HashBiMap.create();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
assertEquals("Berlin", capitalCountryMap.inverse().get("Germany"));
}
}

View File

@@ -0,0 +1,227 @@
package com.baeldung.map;
import org.apache.commons.collections4.MultiMapUtils;
import org.apache.commons.collections4.MultiSet;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class MultiValuedMapUnitTest {
@Test
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple", "orange");
}
@Test
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.putAll("vehicles", Arrays.asList("car", "bike"));
assertThat((Collection<String>) map.get("vehicles")).containsExactly("car", "bike");
}
@Test
public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple");
}
@Test
public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
Collection<Entry<String, String>> entries = (Collection<Entry<String, String>>) map.entries();
for(Map.Entry<String,String> entry : entries) {
assertThat(entry.getKey()).contains("fruits");
assertTrue(entry.getValue().equals("apple") || entry.getValue().equals("orange") );
}
}
@Test
public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
MultiSet<String> keys = map.keys();
assertThat((keys)).contains("fruits", "vehicles");
}
@Test
public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
Set<String> keys = map.keySet();
assertThat(keys).contains("fruits", "vehicles");
}
@Test
public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
}
@Test
public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.remove("fruits");
assertThat(((Collection<String>) map.values())).contains("car", "bike");
}
@Test
public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.removeMapping("fruits", "apple");
assertThat(((Collection<String>) map.values())).contains("orange", "car", "bike");
}
@Test
public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.clear();
assertTrue(map.isEmpty());
}
@Test
public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertTrue(map.containsKey("fruits"));
}
@Test
public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertTrue(map.containsValue("orange"));
}
@Test
public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertFalse(map.isEmpty());
}
@Test
public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertEquals(4, map.size());
}
@Test
public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("fruits", "orange");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple", "orange", "orange");
}
@Test
public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() {
MultiValuedMap<String, String> map = new HashSetValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "apple");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple");
}
@Test(expected = UnsupportedOperationException.class)
public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
MultiValuedMap<String, String> immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map);
immutableMap.put("fruits", "banana");
}
}

View File

@@ -11,3 +11,4 @@ This module contains articles about the Java Set collection
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
- [Set Operations in Java](https://www.baeldung.com/java-set-operations)
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)

View File

@@ -34,7 +34,23 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<commons-collections4.version>4.3</commons-collections4.version>
<gson.version>2.8.5</gson.version>
</properties>

View File

@@ -1,4 +1,4 @@
package com.baeldung.java9.set;
package com.baeldung.set;
import com.google.common.collect.ImmutableSet;

View File

@@ -1,9 +1,10 @@
package com.baeldung.java9;
package com.baeldung.set;
import org.junit.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

View File

@@ -3,7 +3,6 @@
This module contains articles about Java collections
### Relevant Articles:
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
- [Introduction to the Java ArrayDeque](https://www.baeldung.com/java-array-deque)
- [An Introduction to Java.util.Hashtable Class](https://www.baeldung.com/java-hash-table)
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
@@ -13,4 +12,4 @@ This module contains articles about Java collections
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)
- [Guide to the Java Queue Interface](https://www.baeldung.com/java-queue)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [[More -->]](/core-java-modules/core-java-collections-2)
- [[More -->]](/core-java-modules/core-java-collections-2)

View File

@@ -10,4 +10,5 @@ This module contains articles about advanced topics about multithreading with co
- [Guide to RejectedExecutionHandler](https://www.baeldung.com/java-rejectedexecutionhandler)
- [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing)
- [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming)
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@@ -0,0 +1,25 @@
package com.baeldung.concurrent.volatilekeyword;
public class TaskRunner {
private static int number;
private volatile static boolean ready;
private static class Reader extends Thread {
@Override
public void run() {
while (!ready) {
Thread.yield();
}
System.out.println(number);
}
}
public static void main(String[] args) {
new Reader().start();
number = 42;
ready = true;
}
}

View File

@@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency
- [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep)
- [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized)
- [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)

View File

@@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping)

View File

@@ -0,0 +1,7 @@
=========
## Core Java Concurrency Testing Examples
### Relevant Articles:
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)

View File

@@ -0,0 +1,93 @@
<?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-concurrency-testing</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-testing</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>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.thread-weaver</groupId>
<artifactId>threadweaver</artifactId>
<version>0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.tempus-fugit</groupId>
<artifactId>tempus-fugit</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.multithreadedtc</groupId>
<artifactId>multithreadedtc</artifactId>
<version>1.01</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jcstress</groupId>
<artifactId>jcstress-core</artifactId>
<version>0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<compilerVersion>${javac.target}</compilerVersion>
<source>${javac.target}</source>
<target>${javac.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>main</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>jcstress</finalName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jcstress.Main</mainClass>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/TestList</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,22 @@
package com.baeldung.concurrent;
public class MyCounter {
private int count;
public void increment() {
int temp = count;
count = temp + 1;
}
public synchronized void incrementWithWait() throws InterruptedException {
int temp = count;
wait(100);
count = temp + 1;
}
public int getCount() {
return count;
}
}

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,36 @@
package com.baeldung.concurrent;
import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE;
import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE_INTERESTING;
import org.openjdk.jcstress.annotations.Actor;
import org.openjdk.jcstress.annotations.Arbiter;
import org.openjdk.jcstress.annotations.JCStressTest;
import org.openjdk.jcstress.annotations.Outcome;
import org.openjdk.jcstress.annotations.State;
import org.openjdk.jcstress.infra.results.I_Result;
@JCStressTest
@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.")
@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.")
@State
public class MyCounterJCStressUnitTest {
private MyCounter counter;
@Actor
public void actor1() {
counter.increment();
}
@Actor
public void actor2() {
counter.increment();
}
@Arbiter
public void arbiter(I_Result r) {
r.r1 = counter.getCount();
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.concurrent;
import org.junit.Test;
import edu.umd.cs.mtc.MultithreadedTestCase;
import edu.umd.cs.mtc.TestFramework;
public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
private MyCounter counter;
@Override
public void initialize() {
counter = new MyCounter();
}
public void thread1() throws InterruptedException {
counter.increment();
}
public void thread2() throws InterruptedException {
counter.increment();
}
@SuppressWarnings("deprecation")
@Override
public void finish() {
assertEquals(2, counter.getCount());
}
@Test
public void testCounter() throws Throwable {
TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000);
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
public class MyCounterSimpleUnitTest {
@Test
public void testCounter() {
MyCounter counter = new MyCounter();
for (int i = 0; i < 500; i++)
counter.increment();
assertEquals(500, counter.getCount());
}
// @Test
public void testCounterWithConcurrency() throws InterruptedException {
int numberOfThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
MyCounter counter = new MyCounter();
for (int i = 0; i < numberOfThreads; i++) {
service.execute(() -> {
counter.increment();
latch.countDown();
});
}
latch.await();
assertEquals(numberOfThreads, counter.getCount());
}
// @Test
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
int numberOfThreads = 2;
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
MyCounter counter = new MyCounter();
for (int i = 0; i < numberOfThreads; i++) {
service.submit(() -> {
try {
counter.incrementWithWait();
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
});
}
latch.await();
assertEquals(numberOfThreads, counter.getCount());
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import com.google.code.tempusfugit.concurrency.ConcurrentRule;
import com.google.code.tempusfugit.concurrency.RepeatingRule;
import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
import com.google.code.tempusfugit.concurrency.annotations.Repeating;
public class MyCounterTempusFugitUnitTest {
@Rule
public ConcurrentRule concurrently = new ConcurrentRule();
@Rule
public RepeatingRule rule = new RepeatingRule();
private static MyCounter counter = new MyCounter();
@Test
@Concurrent(count = 2)
@Repeating(repetition = 10)
public void runsMultipleTimes() {
counter.increment();
}
@AfterClass
public static void annotatedTestRunsMultipleTimes() throws InterruptedException {
assertEquals(counter.getCount(), 20);
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.google.testing.threadtester.AnnotatedTestRunner;
import com.google.testing.threadtester.ThreadedAfter;
import com.google.testing.threadtester.ThreadedBefore;
import com.google.testing.threadtester.ThreadedMain;
import com.google.testing.threadtester.ThreadedSecondary;
public class MyCounterThreadWeaverUnitTest {
private MyCounter counter;
@ThreadedBefore
public void before() {
counter = new MyCounter();
}
@ThreadedMain
public void mainThread() {
counter.increment();
}
@ThreadedSecondary
public void secondThread() {
counter.increment();
}
@ThreadedAfter
public void after() {
assertEquals(2, counter.getCount());
}
@Test
public void testCounter() {
new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class);
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -7,4 +7,5 @@ This module contains articles about date operations in Java.
- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime)
- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone)
- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)

View File

@@ -12,4 +12,5 @@ This module contains articles about core Java input and output (IO)
- [Java Append Data to a File](https://www.baeldung.com/java-append-to-file)
- [How to Copy a File with Java](https://www.baeldung.com/java-copy-file)
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
- [Java IO vs NIO](https://www.baeldung.com/java-io-vs-nio)
- [[<-- Prev]](/core-java-modules/core-java-io)

View File

@@ -1,18 +1,17 @@
package com.baeldung.java8;
import static org.hamcrest.Matchers.equalTo;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import static org.hamcrest.Matchers.equalTo;
public class Java8SortUnitTest {
@@ -113,11 +112,11 @@ public class Java8SortUnitTest {
humans.sort(Comparator.comparing(Human::getName));
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<String> letters = Lists.newArrayList("B", "A", "C");
final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
Assert.assertThat(sortedLetters.get(0), equalTo("A"));
}
@@ -126,7 +125,7 @@ public class Java8SortUnitTest {
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
@@ -164,4 +163,48 @@ public class Java8SortUnitTest {
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
}
@Test(expected = NullPointerException.class)
public final void givenANullElement_whenSortingEntitiesByName_thenThrowsNPE() {
final List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12));
humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
}
@Test
public final void givenANullElement_whenSortingEntitiesByNameManually_thenMovesTheNullToLast() {
final List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12), null);
humans.sort((h1, h2) -> {
if (h1 == null) return h2 == null ? 0 : 1;
else if (h2 == null) return -1;
return h1.getName().compareTo(h2.getName());
});
Assert.assertNotNull(humans.get(0));
Assert.assertNull(humans.get(1));
Assert.assertNull(humans.get(2));
}
@Test
public final void givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToLast() {
final List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12), null);
humans.sort(Comparator.nullsLast(Comparator.comparing(Human::getName)));
Assert.assertNotNull(humans.get(0));
Assert.assertNull(humans.get(1));
Assert.assertNull(humans.get(2));
}
@Test
public final void givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToStart() {
final List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12), null);
humans.sort(Comparator.nullsFirst(Comparator.comparing(Human::getName)));
Assert.assertNull(humans.get(0));
Assert.assertNull(humans.get(1));
Assert.assertNotNull(humans.get(2));
}
}

View File

@@ -10,4 +10,5 @@ This module contains articles about core features in the Java language
- [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values)
- [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword)
- [The Java Headless Mode](https://www.baeldung.com/java-headless-mode)
- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values)
- [[<-- Prev]](/core-java-modules/core-java-lang)

View File

@@ -0,0 +1,84 @@
package com.baeldung.comparelong;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import org.junit.Test;
import java.util.Objects;
public class CompareLongUnitTest {
@Test
public void givenLongValuesLessThan128_whenUsingReferenceComparater_thenSuccess() {
Long l1 = 127L;
Long l2 = 127L;
assertThat(l1 == l2).isTrue();
}
@Test
public void givenLongValuesGreaterOrEqualsThan128_whenUsingReferenceComparater_thenFails() {
Long l1 = 128L;
Long l2 = 128L;
assertThat(l1 == l2).isFalse();
}
@Test
public void givenLongValuesGreaterOrEqualsThan128_whenUsingEquals_thenSuccess() {
Long l1 = 128L;
Long l2 = 128L;
assertThat(l1.equals(l2)).isTrue();
}
@Test
public void givenLongValuesLessThan128_whenUsingObjectsEquals_thenSuccess() {
Long l1 = 127L;
Long l2 = 127L;
assertThat(Objects.equals(l1, l2)).isTrue();
}
@Test
public void givenLongValuesGreaterOrEqualsThan128_whenUsingObjectsEquals_thenSuccess() {
Long l1 = 128L;
Long l2 = 128L;
assertThat(Objects.equals(l1, l2)).isTrue();
}
@Test
public void givenNullReference_whenUsingObjectsEquals_thenNoException() {
Long l1 = null;
Long l2 = 128L;
assertThatCode(() -> Objects.equals(l1, l2)).doesNotThrowAnyException();
}
@Test
public void givenLongValuesGreaterOrEqualsThan128_whenUsingComparisonOperator_andLongValue_thenSuccess() {
Long l1 = 128L;
Long l2 = 128L;
assertThat(l1.longValue() == l2.longValue()).isTrue();
}
@Test
public void givenLongValuesGreaterOrEqualsThan128_whenUsingCasting_thenSuccess() {
Long l1 = 128L;
Long l2 = 128L;
assertThat((long) l1 == (long) l2).isTrue();
}
}

View File

@@ -3,7 +3,12 @@ package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.*;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
public class JMXTutorialMainlauncher {
@@ -11,24 +16,21 @@ public class JMXTutorialMainlauncher {
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
public static void main(String[] args) {
// TODO Auto-generated method stub
LOG.debug("This is basic JMX tutorial");
ObjectName objectName = null;
try {
objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game");
} catch (MalformedObjectNameException e) {
e.printStackTrace();
}
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
Game gameObj = new Game();
try {
server.registerMBean(gameObj, objectName);
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
ObjectName objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game");
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
server.registerMBean(new Game(), objectName);
} catch (MalformedObjectNameException | InstanceAlreadyExistsException |
MBeanRegistrationException | NotCompliantMBeanException e) {
e.printStackTrace();
}
LOG.debug("Registration for Game mbean with the platform server is successfull");
LOG.debug("Please open jconsole to access Game mbean");
while (true) {
// to ensure application does not terminate
}

View File

@@ -9,3 +9,4 @@
- [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile)
- [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches)
- [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement)
- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus)

View File

@@ -1,3 +1,12 @@
## Core Java Security
This module contains articles about core Java Security
### Relevant Articles:
- [Guide To The Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
- [Checksums in Java](https://www.baeldung.com/java-checksums)
- More articles: [[<-- prev]](/core-java-modules/core-java-security)

View File

@@ -16,4 +16,45 @@
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<properties>
<!-- util -->
<bouncycastle.version>1.60</bouncycastle.version>
<commons-codec.version>1.11</commons-codec.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@@ -0,0 +1,23 @@
package com.baeldung.checksums;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;
public class ChecksumUtils {
public static long getChecksumCRC32(byte[] bytes) {
Checksum crc32 = new CRC32();
crc32.update(bytes, 0, bytes.length);
return crc32.getValue();
}
public static long getChecksumCRC32(InputStream stream, int bufferSize) throws IOException {
CheckedInputStream checkedInputStream = new CheckedInputStream(stream, new CRC32());
byte[] buffer = new byte[bufferSize];
while (checkedInputStream.read(buffer, 0, buffer.length) >= 0) {}
return checkedInputStream.getChecksum().getValue();
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.checksums;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.*;
class ChecksumUtilsUnitTest {
byte[] arr;
@Before
void setUp() {
arr = new byte[]{0,10,21,20,35,40,120,56,72,22};
}
@Test
void givenByteArray_whenChecksumCreated_checkCorrect() {
long checksum = ChecksumUtils.getChecksumCRC32(arr);
assertEquals(3915397664L, checksum);
}
@Test
void givenTwoDifferentStrings_whenChecksumCreated_checkCollision() {
String plumless = "plumless";
String buckeroo = "buckeroo";
long plumlessChecksum = ChecksumUtils.getChecksumCRC32(plumless.getBytes());
long buckerooChecksum = ChecksumUtils.getChecksumCRC32(buckeroo.getBytes());
assertEquals(plumlessChecksum, buckerooChecksum);
}
@Test
void givenInputString_whenChecksumCreated_checkCorrect() throws IOException {
InputStream inputStream = new ByteArrayInputStream(arr);
long checksum = ChecksumUtils.getChecksumCRC32(inputStream, 10);
assertEquals(3915397664L, checksum);
}
}

View File

@@ -3,17 +3,16 @@
This module contains articles about core Java Security
### Relevant Articles:
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream)
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
- [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12)
- [The Java SecureRandom Class](https://www.baeldung.com/java-secure-random)
- [An Introduction to Java SASL](https://www.baeldung.com/java-sasl)
- [A Guide to Java GSS API](https://www.baeldung.com/java-gss)
- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager)
- More articles: [[next -->]](/core-java-modules/core-java-security-2)

View File

@@ -24,24 +24,9 @@
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
</dependencies>
<properties>
<!-- util -->
<bouncycastle.version>1.60</bouncycastle.version>
<commons-codec.version>1.11</commons-codec.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>

View File

@@ -9,4 +9,5 @@ This module contains articles about the Stream API in Java.
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
- [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams)
- [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals)
- More articles: [[<-- prev>]](/../core-java-streams-2)

View File

@@ -0,0 +1,42 @@
package com.baeldung.streams.bigdecimals;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
public class AddNumbersUnitTest {
@Test
public void givenIntStream_whenSum_thenResultIsCorrect() {
IntStream intNumbers = IntStream.range(0, 3);
assertEquals(3, intNumbers.sum());
}
@Test
public void givenCollectionOfDouble_whenUsingMapToDoubleToSum_thenResultIsCorrect() {
List<Double> doubleNumbers = Arrays.asList(23.48, 52.26, 13.5);
double result = doubleNumbers.stream()
.mapToDouble(Double::doubleValue)
.sum();
assertEquals(89.24, result, .1);
}
public void givenStreamOfIntegers_whenUsingReduceToSum_thenResultIsCorrect() {
Stream<Integer> intNumbers = Stream.of(0, 1, 2);
int result = intNumbers.reduce(0, Integer::sum);
assertEquals(106, result);
}
public void givenStreamOfBigDecimals_whenUsingReduceToSum_thenResultIsCorrect() {
Stream<BigDecimal> bigDecimalNumber = Stream.of(BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN);
BigDecimal result = bigDecimalNumber.reduce(BigDecimal.ZERO, BigDecimal::add);
assertEquals(11, result);
}
}

View File

@@ -11,4 +11,5 @@ This module contains articles about string operations.
- [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching)
- [L-Trim and R-Trim in Java](https://www.baeldung.com/l-trim-and-r-trim-in-java)
- [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives)
- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64)
- More articles: [[<-- prev]](../core-java-string-operations)

View File

@@ -38,6 +38,11 @@ public class AddingNewLineToString {
System.out.println("6. Using System.getProperty(\"line.separator\")");
rhyme = line1 + System.getProperty("line.separator") + line2;
System.out.println(rhyme);
//7. Using %n
System.out.println("7. Using %n");
rhyme = "Humpty Dumpty sat on a wall.%nHumpty Dumpty had a great fall.";
System.out.println(rhyme);
System.out.println("***HTML to rendered in a browser***");
//1. Line break for HTML using <br>

View File

@@ -12,3 +12,4 @@ This module contains articles about strings in Java.
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string)
- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool)
- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error)

View File

@@ -42,7 +42,10 @@
<module>core-java-collections-list</module>
<module>core-java-collections-list-2</module>
<module>core-java-collections-list-3</module>
<module>core-java-collections-set</module>
<module>core-java-collections-maps</module>
<module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module>
<!-- <module>core-java-collections-set</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<module>core-java-concurrency-2</module>
<module>core-java-concurrency-advanced</module>