JAVA-11533 Move core-java related modules to core-java-modules (#12119)

* JAVA-11533 Move core-java related modules to core-java-modules

* JAVA-11533 Remove moved modules from old parent pom

* JAVA-11533 Updated Readme and pom of parent module

* JAVA-11533 Revert changes made to Readme of parent module

* JAVA-11533 Moved articles to respective submouldes
This commit is contained in:
anuragkumawat
2022-05-04 20:15:22 +05:30
committed by GitHub
parent 936e517731
commit 9990d103cd
58 changed files with 12 additions and 17 deletions
+2 -2
View File
@@ -4,6 +4,6 @@ This module contains modules about core Java
## Relevant articles:
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
@@ -13,4 +13,5 @@ This module contains articles about core java exceptions
- [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error)
- [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions)
- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions)
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
- [[Next -->]](/core-java-modules/core-java-exceptions-2)
@@ -0,0 +1,12 @@
## Java Collections Cookbooks and Examples
This module contains articles about conversions among Collection types and arrays in Java.
### Relevant Articles:
- [Array to String Conversions](https://www.baeldung.com/java-array-to-string)
- [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists)
- [Converting List to Map With a Custom Supplier](https://www.baeldung.com/list-to-map-supplier)
- [Arrays.asList vs new ArrayList(Arrays.asList())](https://www.baeldung.com/java-arrays-aslist-vs-new-arraylist)
- [Iterate Over a Set in Java](https://www.baeldung.com/java-iterate-set)
- More articles: [[<-- prev]](../java-collections-conversions)
@@ -0,0 +1,45 @@
<?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>java-collections-conversions-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-collections-conversions-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>${modelmapper.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>0.10.3</version>
</dependency>
</dependencies>
<build>
<finalName>java-collections-conversions-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
@@ -0,0 +1,70 @@
package com.baeldung.convertlisttomap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Convert a string list to a map whose key is the string's length and value is the collection with same length.
* Give a list {"Baeldung", "is", "very", "cool"}.
* After conversion we'll get a map like:
* {8 : ["Baeldung"], 2 : ["is"], 4 : ["very", "cool"]}.
*
* @author leasy.zhang
*
*/
public class ListToMapConverter {
public Map<Integer, List<String>> groupingByStringLength(List<String> source,
Supplier<Map<Integer, List<String>>> mapSupplier,
Supplier<List<String>> listSupplier) {
return source.stream()
.collect(Collectors.groupingBy(String::length, mapSupplier, Collectors.toCollection(listSupplier)));
}
public Map<Integer, List<String>> streamCollectByStringLength(List<String> source,
Supplier<Map<Integer, List<String>>> mapSupplier,
Supplier<List<String>> listSupplier) {
BiConsumer<Map<Integer, List<String>>, String> accumulator = (response, element) -> {
Integer key = element.length();
List<String> values = response.getOrDefault(key, listSupplier.get());
values.add(element);
response.put(key, values);
};
BiConsumer<Map<Integer, List<String>>, Map<Integer, List<String>>> combiner = (res1, res2) -> {
res1.putAll(res2);
};
return source.stream()
.collect(mapSupplier, accumulator, combiner);
}
public Map<Integer, List<String>> collectorToMapByStringLength(List<String> source,
Supplier<Map<Integer, List<String>>> mapSupplier,
Supplier<List<String>> listSupplier) {
Function<String, Integer> keyMapper = String::length;
Function<String, List<String>> valueMapper = (element) -> {
List<String> collection = listSupplier.get();
collection.add(element);
return collection;
};
BinaryOperator<List<String>> mergeFunction = (existing, replacement) -> {
existing.addAll(replacement);
return existing;
};
return source.stream()
.collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier));
}
}
@@ -0,0 +1,32 @@
package com.baeldung.modelmapper;
import org.modelmapper.ModelMapper;
import java.util.List;
import java.util.stream.Collectors;
/**
* This is a helper class that contains method for custom mapping of the users list.
* Initially, an instance of ModelMapper was created.
*
* @author Sasa Milenkovic
*/
public class MapperUtil {
private static ModelMapper modelMapper = new ModelMapper();
private MapperUtil() {
}
public static <S, T> List<T> mapList(List<S> source, Class<T> targetClass) {
return source
.stream()
.map(element -> modelMapper.map(element, targetClass))
.collect(Collectors.toList());
}
}
@@ -0,0 +1,70 @@
package com.baeldung.modelmapper;
/**
* User model entity class
*
* @author Sasa Milenkovic
*/
public class User {
private String userId;
private String username;
private String email;
private String contactNumber;
private String userType;
// Standard constructors, getters and setters
public User() {
}
public User(String userId, String username, String email, String contactNumber, String userType) {
this.userId = userId;
this.username = username;
this.email = email;
this.contactNumber = contactNumber;
this.userType = userType;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String userName) {
this.username = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.modelmapper;
/**
* UserDTO model class
*
* @author Sasa Milenkovic
*/
public class UserDTO {
private String userId;
private String username;
private String email;
// getters and setters
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.modelmapper;
import java.util.Collection;
/**
* UserList class that contain collection of users
*
* @author Sasa Milenkovic
*/
public class UserList {
private Collection<User> users;
public Collection<User> getUsers() {
return users;
}
public void setUsers(Collection<User> users) {
this.users = users;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.modelmapper;
import java.util.List;
/**
* UserListDTO class that contain list of username properties
*
* @author Sasa Milenkovic
*/
public class UserListDTO {
private List<String> usernames;
public List<String> getUsernames() {
return usernames;
}
public void setUsernames(List<String> usernames) {
this.usernames = usernames;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.modelmapper;
import org.modelmapper.AbstractConverter;
import java.util.List;
import java.util.stream.Collectors;
/**
* UsersListConverter class map the property data from the list of users into the list of user names.
*
* @author Sasa Milenkovic
*/
public class UsersListConverter extends AbstractConverter<List<User>, List<String>> {
@Override
protected List<String> convert(List<User> users) {
return users
.stream()
.map(User::getUsername)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,35 @@
package com.baeldung.arrayconversion;
import org.assertj.core.api.ListAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ArrayToListConversionUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() {
String[] stringArray = new String[] { "A", "B", "C", "D" };
List<String> stringList = Arrays.asList(stringArray);
stringList.set(0, "E");
assertThat(stringList).containsExactly("E", "B", "C", "D");
assertThat(stringArray).containsExactly("E", "B", "C", "D");
stringList.add("F");
}
@Test
public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() {
String[] stringArray = new String[] { "A", "B", "C", "D" };
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
stringList.set(0, "E");
assertThat(stringList).containsExactly("E", "B", "C", "D");
assertThat(stringArray).containsExactly("A", "B", "C", "D");
stringList.add("F");
assertThat(stringList).containsExactly("E", "B", "C", "D", "F");
}
}
@@ -0,0 +1,135 @@
package com.baeldung.convertarraytostring;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
public class ArrayToStringUnitTest {
// convert with Java
@Test
public void givenAStringArray_whenConvertBeforeJava8_thenReturnString() {
String[] strArray = { "Convert", "Array", "With", "Java" };
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strArray.length; i++) {
stringBuilder.append(strArray[i]);
}
String joinedString = stringBuilder.toString();
assertThat(joinedString, instanceOf(String.class));
assertEquals("ConvertArrayWithJava", joinedString);
}
@Test
public void givenAString_whenConvertBeforeJava8_thenReturnStringArray() {
String input = "lorem ipsum dolor sit amet";
String[] strArray = input.split(" ");
assertThat(strArray, instanceOf(String[].class));
assertEquals(5, strArray.length);
input = "loremipsum";
strArray = input.split("");
assertThat(strArray, instanceOf(String[].class));
assertEquals(10, strArray.length);
}
@Test
public void givenAnIntArray_whenConvertBeforeJava8_thenReturnString() {
int[] strArray = { 1, 2, 3, 4, 5 };
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strArray.length; i++) {
stringBuilder.append(Integer.valueOf(strArray[i]));
}
String joinedString = stringBuilder.toString();
assertThat(joinedString, instanceOf(String.class));
assertEquals("12345", joinedString);
}
// convert with Java Stream API
@Test
public void givenAStringArray_whenConvertWithJavaStream_thenReturnString() {
String[] strArray = { "Convert", "With", "Java", "Streams" };
String joinedString = Arrays.stream(strArray)
.collect(Collectors.joining());
assertThat(joinedString, instanceOf(String.class));
assertEquals("ConvertWithJavaStreams", joinedString);
joinedString = Arrays.stream(strArray)
.collect(Collectors.joining(","));
assertThat(joinedString, instanceOf(String.class));
assertEquals("Convert,With,Java,Streams", joinedString);
}
// convert with Apache Commons
@Test
public void givenAStringArray_whenConvertWithApacheCommons_thenReturnString() {
String[] strArray = { "Convert", "With", "Apache", "Commons" };
String joinedString = StringUtils.join(strArray);
assertThat(joinedString, instanceOf(String.class));
assertEquals("ConvertWithApacheCommons", joinedString);
}
@Test
public void givenAString_whenConvertWithApacheCommons_thenReturnStringArray() {
String input = "lorem ipsum dolor sit amet";
String[] strArray = StringUtils.split(input, " ");
assertThat(strArray, instanceOf(String[].class));
assertEquals(5, strArray.length);
}
// convert with Guava
@Test
public void givenAStringArray_whenConvertWithGuava_thenReturnString() {
String[] strArray = { "Convert", "With", "Guava", null };
String joinedString = Joiner.on("")
.skipNulls()
.join(strArray);
assertThat(joinedString, instanceOf(String.class));
assertEquals("ConvertWithGuava", joinedString);
}
@Test
public void givenAString_whenConvertWithGuava_thenReturnStringArray() {
String input = "lorem ipsum dolor sit amet";
List<String> resultList = Splitter.on(' ')
.trimResults()
.omitEmptyStrings()
.splitToList(input);
String[] strArray = resultList.toArray(new String[0]);
assertThat(strArray, instanceOf(String[].class));
assertEquals(5, strArray.length);
}
}
@@ -0,0 +1,46 @@
package com.baeldung.convertlisttomap;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class ListToMapUnitTest {
private ListToMapConverter converter;
private List<String> source;
@Before
public void setUp() {
converter = new ListToMapConverter();
source = Arrays.asList("List", "Map", "Set", "Tree");
}
@Test
public void givenAList_whenConvertWithJava8GroupBy_thenReturnMap() {
Map<Integer, List<String>> convertedMap = converter.groupingByStringLength(source, HashMap::new, ArrayList::new);
assertTrue(convertedMap.get(3)
.contains("Map"));
}
@Test
public void givenAList_whenConvertWithJava8Collect_thenReturnMap() {
Map<Integer, List<String>> convertedMap = converter.streamCollectByStringLength(source, HashMap::new, ArrayList::new);
assertTrue(convertedMap.get(3)
.contains("Map"));
}
@Test
public void givenAList_whenConvertWithCollectorToMap_thenReturnMap() {
Map<Integer, List<String>> convertedMap = converter.collectorToMapByStringLength(source, HashMap::new, ArrayList::new);
assertTrue(convertedMap.get(3)
.contains("Map"));
}
}
@@ -0,0 +1,92 @@
package com.baeldung.modelmapper;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeMap;
import org.modelmapper.TypeToken;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertThat;
/**
* This class has test methods of mapping Integer to Character list,
* mapping users list to DTO list using MapperUtil custom type method and property mapping using converter class
*
* @author Sasa Milenkovic
*/
public class UsersListMappingUnitTest {
private ModelMapper modelMapper;
private List<User> users;
@Before
public void init() {
modelMapper = new ModelMapper();
TypeMap<UserList, UserListDTO> typeMap = modelMapper.createTypeMap(UserList.class, UserListDTO.class);
typeMap.addMappings(mapper -> mapper.using(new UsersListConverter())
.map(UserList::getUsers, UserListDTO::setUsernames));
users = new ArrayList();
users.add(new User("b100", "user1", "user1@baeldung.com", "111-222", "USER"));
users.add(new User("b101", "user2", "user2@baeldung.com", "111-333", "USER"));
users.add(new User("b102", "user3", "user3@baeldung.com", "111-444", "ADMIN"));
}
@Test
public void whenInteger_thenMapToCharacter() {
List<Integer> integers = new ArrayList<Integer>();
integers.add(1);
integers.add(2);
integers.add(3);
List<Character> characters = modelMapper.map(integers, new TypeToken<List<Character>>() {
}.getType());
assertThat(characters, hasItems('1', '2', '3'));
}
@Test
public void givenUsersList_whenUseGenericType_thenMapToUserDTO() {
// Mapping lists using custom (generic) type mapping
List<UserDTO> userDtoList = MapperUtil.mapList(users, UserDTO.class);
assertThat(userDtoList, Matchers.<UserDTO>hasItem(
Matchers.both(hasProperty("userId", equalTo("b100")))
.and(hasProperty("email", equalTo("user1@baeldung.com")))
.and(hasProperty("username", equalTo("user1")))));
}
@Test
public void givenUsersList_whenUseConverter_thenMapToUsernames() {
// Mapping lists using property mapping and converter
UserList userList = new UserList();
userList.setUsers(users);
UserListDTO dtos = new UserListDTO();
modelMapper.map(userList, dtos);
assertThat(dtos.getUsernames(), hasItems("user1", "user2", "user3"));
}
}
@@ -0,0 +1,74 @@
package com.baeldung.setiteration;
import com.google.common.collect.Sets;
import io.vavr.collection.Stream;
import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
class SetIteration {
@Test
void givenSet_whenIteratorUsed_shouldIterateOverElements() {
// given
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
// when
Iterator<String> namesIterator1 = names.iterator();
Iterator<String> namesIterator2 = names.iterator();
// then
namesIterator1.forEachRemaining(System.out::println);
while(namesIterator2.hasNext()) {
System.out.println(namesIterator2.next());
}
}
@Test
void givenSet_whenStreamUsed_shouldIterateOverElements() {
// given
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
// when & then
String namesJoined = names.stream()
.map(String::toUpperCase)
.peek(System.out::println)
.collect(Collectors.joining());
}
@Test
void givenSet_whenEnhancedLoopUsed_shouldIterateOverElements() {
// given
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
// when & then
for (String name : names) {
System.out.println(name);
}
}
@Test
void givenSet_whenMappedToArray_shouldIterateOverElements() {
// given
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
// when & then
Object[] namesArray = names.toArray();
for (int i = 0; i < namesArray.length; i++) {
System.out.println(i + ": " + namesArray[i]);
}
}
@Test
void givenSet_whenZippedWithIndex_shouldIterateOverElements() {
// given
Set<String> names = Sets.newHashSet("Tom", "Jane", "Karen");
// when & then
Stream.ofAll(names)
.zipWithIndex()
.forEach(t -> System.out.println(t._2() + ": " + t._1()));
}
}
@@ -0,0 +1,15 @@
## Java Collections Cookbooks and Examples
This module contains articles about conversions among Collection types and arrays in Java.
### Relevant Articles:
- [Converting between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array)
- [Converting between an Array and a Set in Java](https://www.baeldung.com/convert-array-to-set-and-set-to-array)
- [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set)
- [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string)
- [How to Convert List to Map in Java](https://www.baeldung.com/java-list-to-map)
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
- [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap)
- [Converting Iterable to Collection in Java](https://www.baeldung.com/java-iterable-to-collection)
- [Converting Iterator to List](https://www.baeldung.com/java-convert-iterator-to-list)
- More articles: [[next -->]](../java-collections-conversions-2)
@@ -0,0 +1,40 @@
<?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>java-collections-conversions</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-collections-conversions</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<build>
<finalName>java-collections-conversions</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
@@ -0,0 +1,48 @@
package com.baeldung.convertToMap;
public class Book {
private String name;
private int releaseYear;
private String isbn;
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", releaseYear=" + releaseYear +
", isbn='" + isbn + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(int releaseYear) {
this.releaseYear = releaseYear;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Book(String name, int releaseYear, String isbn) {
this.name = name;
this.releaseYear = releaseYear;
this.isbn = isbn;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.convertToMap;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ConvertToMap {
public Map<String, String> listToMap(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getIsbn, Book::getName));
}
public Map<Integer, Book> listToMapWithDupKeyError(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity()));
}
public Map<Integer, Book> listToMapWithDupKey(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), (existing, replacement) -> existing));
}
public Map<Integer, Book> listToConcurrentMap(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), (o1, o2) -> o1, ConcurrentHashMap::new));
}
public TreeMap<String, Book> listToSortedMap(List<Book> books) {
return books.stream()
.collect(Collectors.toMap(Book::getName, Function.identity(), (o1, o2) -> o1, TreeMap::new));
}
}
@@ -0,0 +1,52 @@
package com.baeldung.convertcollectiontoarraylist;
/**
* This POJO is the element type of our collection. It has a deepCopy() method.
*
* @author chris
*/
public class Foo {
private int id;
private String name;
private Foo parent;
public Foo() {
}
public Foo(int id, String name, Foo parent) {
this.id = id;
this.name = name;
this.parent = parent;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Foo getParent() {
return parent;
}
public void setParent(Foo parent) {
this.parent = parent;
}
public Foo deepCopy() {
return new Foo(
this.id, this.name, this.parent != null ? this.parent.deepCopy() : null);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.convertlisttomap;
public class Animal {
private int id;
private String name;
public Animal(int id, String name) {
this.id = id;
this.setName(name);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.convertlisttomap;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.MapUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ConvertListToMapService {
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
for (Animal animal : list) {
map.put(animal.getId(), animal);
}
return map;
}
public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
Map<Integer, Animal> map = list.stream().collect(Collectors.toMap(Animal::getId, Function.identity()));
return map;
}
public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
Map<Integer, Animal> map = Maps.uniqueIndex(list, Animal::getId);
return map;
}
public Map<Integer, Animal> convertListWithApacheCommons(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
MapUtils.populateMap(map, list, Animal::getId);
return map;
}
}
@@ -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>
@@ -0,0 +1,53 @@
package com.baeldung.convertToMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class ConvertToMapUnitTest {
private List<Book> bookList;
private ConvertToMap convertToMap = new ConvertToMap();
@Before
public void init() {
bookList = new ArrayList<>();
bookList.add(new Book("The Fellowship of the Ring", 1954, "0395489318"));
bookList.add(new Book("The Two Towers", 1954, "0345339711"));
bookList.add(new Book("The Return of the King", 1955, "0618129111"));
}
@Test
public void whenConvertFromListToMap() {
assertTrue(convertToMap.listToMap(bookList).size() == 3);
}
@Test(expected = IllegalStateException.class)
public void whenMapHasDuplicateKey_without_merge_function_then_runtime_exception() {
convertToMap.listToMapWithDupKeyError(bookList);
}
@Test
public void whenMapHasDuplicateKeyThenMergeFunctionHandlesCollision() {
Map<Integer, Book> booksByYear = convertToMap.listToMapWithDupKey(bookList);
assertEquals(2, booksByYear.size());
assertEquals("0395489318", booksByYear.get(1954).getIsbn());
}
@Test
public void whenCreateConcurrentHashMap() {
assertTrue(convertToMap.listToConcurrentMap(bookList) instanceof ConcurrentHashMap);
}
@Test
public void whenMapisSorted() {
assertTrue(convertToMap.listToSortedMap(bookList).firstKey().equals("The Fellowship of the Ring"));
}
}
@@ -0,0 +1,145 @@
package com.baeldung.convertcollectiontoarraylist;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import static java.util.stream.Collectors.toCollection;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author chris
*/
public class CollectionToArrayListUnitTest {
private static Collection<Foo> srcCollection = new HashSet<>();
public CollectionToArrayListUnitTest() {
}
@BeforeClass
public static void setUpClass() {
int i = 0;
Foo john = new Foo(i++, "John", null);
Foo mary = new Foo(i++, "Mary", null);
Foo sam = new Foo(i++, "Sam", john);
Foo alice = new Foo(i++, "Alice", john);
Foo buffy = new Foo(i++, "Buffy", sam);
srcCollection.add(john);
srcCollection.add(mary);
srcCollection.add(sam);
srcCollection.add(alice);
srcCollection.add(buffy);
}
/**
* Section 3. Using the ArrayList Constructor
*/
@Test
public void whenUsingConstructor_thenVerifyShallowCopy() {
ArrayList<Foo> newList = new ArrayList<>(srcCollection);
verifyShallowCopy(srcCollection, newList);
}
/**
* Section 4. Using the Streams API
*/
@Test
public void whenUsingStream_thenVerifyShallowCopy() {
ArrayList<Foo> newList = srcCollection.stream().collect(toCollection(ArrayList::new));
verifyShallowCopy(srcCollection, newList);
}
/**
* Section 5. Deep Copy
*/
@Test
public void whenUsingDeepCopy_thenVerifyDeepCopy() {
ArrayList<Foo> newList = srcCollection.stream()
.map(Foo::deepCopy)
.collect(toCollection(ArrayList::new));
verifyDeepCopy(srcCollection, newList);
}
/**
* Section 6. Controlling the List Order
*/
@Test
public void whenUsingSortedStream_thenVerifySortOrder() {
ArrayList<Foo> newList = srcCollection.stream()
.sorted(Comparator.comparing(Foo::getName))
.collect(toCollection(ArrayList::new));
assertTrue("ArrayList is not sorted by name", isSorted(newList));
}
/**
* Verify that the contents of the two collections are the same
* @param a
* @param b
*/
private void verifyShallowCopy(Collection<Foo> a, Collection<Foo> b) {
assertEquals("Collections have different lengths", a.size(), b.size());
Iterator<Foo> iterA = a.iterator();
Iterator<Foo> iterB = b.iterator();
while (iterA.hasNext()) {
// test instance identity
assertSame("Foo instances differ!", iterA.next(), iterB.next());
}
}
/**
* Verify that the contents of the two collections are the same
* @param a
* @param b
*/
private void verifyDeepCopy(Collection<Foo> a, Collection<Foo> b) {
assertEquals("Collections have different lengths", a.size(), b.size());
Iterator<Foo> iterA = a.iterator();
Iterator<Foo> iterB = b.iterator();
while (iterA.hasNext()) {
Foo nextA = iterA.next();
Foo nextB = iterB.next();
// should not be same instance
assertNotSame("Foo instances are the same!", nextA, nextB);
// but should have same content
assertFalse("Foo instances have different content!", fooDiff(nextA, nextB));
}
}
/**
* Return true if the contents of a and b differ. Test parent recursively
* @param a
* @param b
* @return False if the two items are the same
*/
private boolean fooDiff(Foo a, Foo b) {
if (a != null && b != null) {
return a.getId() != b.getId()
|| !a.getName().equals(b.getName())
|| fooDiff(a.getParent(), b.getParent());
}
return !(a == null && b == null);
}
/**
* @param c collection of Foo
* @return true if the collection is sorted by name
*/
private static boolean isSorted(Collection<Foo> c) {
String prevName = null;
for (Foo foo : c) {
if (prevName == null || foo.getName().compareTo(prevName) > 0) {
prevName = foo.getName();
} else {
return false;
}
}
return true;
}
}
@@ -0,0 +1,100 @@
package com.baeldung.convertiteratortolist;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.collections4.IteratorUtils;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class ConvertIteratorToListServiceUnitTest {
Iterator<Integer> iterator;
@Before
public void setUp() {
iterator = Arrays.asList(1, 2, 3)
.iterator();
}
@Test
public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() {
List<Integer> actualList = new ArrayList<>();
// Convert Iterator to List using while loop dsf
while (iterator.hasNext()) {
actualList.add(iterator.next());
}
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() {
List<Integer> actualList = new ArrayList<>();
// Convert Iterator to List using Java 8
iterator.forEachRemaining(actualList::add);
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToListJava8Stream_thenReturnAList() {
// Convert iterator to iterable
Iterable<Integer> iterable = () -> iterator;
// Extract List from stream
List<Integer> actualList = StreamSupport
.stream(iterable.spliterator(), false)
.collect(Collectors.toList());
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToImmutableListWithGuava_thenReturnAList() {
// Convert Iterator to an Immutable list using Guava library in Java
List<Integer> actualList = ImmutableList.copyOf(iterator);
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToMutableListWithGuava_thenReturnAList() {
// Convert Iterator to a mutable list using Guava library in Java
List<Integer> actualList = Lists.newArrayList(iterator);
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToMutableListWithApacheCommons_thenReturnAList() {
// Convert Iterator to a mutable list using Apache Commons library in Java
List<Integer> actualList = IteratorUtils.toList(iterator);
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
}
@@ -0,0 +1,68 @@
package com.baeldung.convertlisttomap;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
public class ConvertListToMapServiceUnitTest {
List<Animal> list;
private ConvertListToMapService convertListService;
@Before
public void init() {
this.convertListService = new ConvertListToMapService();
this.list = new ArrayList<>();
Animal cat = new Animal(1, "Cat");
list.add(cat);
Animal dog = new Animal(2, "Dog");
list.add(dog);
Animal pig = new Animal(3, "Pig");
list.add(pig);
Animal cow = new Animal(4, "Cow");
list.add(cow);
Animal goat = new Animal(5, "Goat");
list.add(goat);
}
@Test
public void givenAList_whenConvertBeforeJava8_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListBeforeJava8(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
@Test
public void givenAList_whenConvertAfterJava8_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListAfterJava8(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
@Test
public void givenAList_whenConvertWithGuava_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListWithGuava(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
@Test
public void givenAList_whenConvertWithApacheCommons_thenReturnMapWithTheSameElements() {
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(list);
assertThat(map.values(), containsInAnyOrder(list.toArray()));
}
}
@@ -0,0 +1,68 @@
package com.baeldung.convertlisttomap;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
public class ConvertListWithDuplicatedIdToMapServiceUnitTest {
List<Animal> duplicatedIdList;
private ConvertListToMapService convertListService = new ConvertListToMapService();
@Before
public void init() {
this.duplicatedIdList = new ArrayList<>();
Animal cat = new Animal(1, "Cat");
duplicatedIdList.add(cat);
Animal dog = new Animal(2, "Dog");
duplicatedIdList.add(dog);
Animal pig = new Animal(3, "Pig");
duplicatedIdList.add(pig);
Animal cow = new Animal(4, "Cow");
duplicatedIdList.add(cow);
Animal goat = new Animal(4, "Goat");
duplicatedIdList.add(goat);
}
@Test
public void givenADupIdList_whenConvertBeforeJava8_thenReturnMapWithRewrittenElement() {
Map<Integer, Animal> map = convertListService.convertListBeforeJava8(duplicatedIdList);
assertThat(map.values(), hasSize(4));
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
}
@Test
public void givenADupIdList_whenConvertWithApacheCommons_thenReturnMapWithRewrittenElement() {
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(duplicatedIdList);
assertThat(map.values(), hasSize(4));
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
}
@Test(expected = IllegalStateException.class)
public void givenADupIdList_whenConvertAfterJava8_thenException() {
convertListService.convertListAfterJava8(duplicatedIdList);
}
@Test(expected = IllegalArgumentException.class)
public void givenADupIdList_whenConvertWithGuava_thenException() {
convertListService.convertListWithGuava(duplicatedIdList);
}
}
@@ -0,0 +1,122 @@
package com.baeldung.java.collections;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.IteratorUtils;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class IterableToCollectionUnitTest {
Iterable<String> iterable = Arrays.asList("john", "tom", "jane");
Iterator<String> iterator = iterable.iterator();
@Test
public void whenConvertIterableToListUsingJava_thenSuccess() {
List<String> result = new ArrayList<String>();
for (String str : iterable) {
result.add(str);
}
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToListUsingJava8_thenSuccess() {
List<String> result = new ArrayList<String>();
iterable.forEach(result::add);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToListUsingJava8WithSpliterator_thenSuccess() {
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
.collect(Collectors.toList());
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToListUsingGuava_thenSuccess() {
List<String> result = Lists.newArrayList(iterable);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToImmutableListUsingGuava_thenSuccess() {
List<String> result = ImmutableList.copyOf(iterable);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToListUsingApacheCommons_thenSuccess() {
List<String> result = IterableUtils.toList(iterable);
assertThat(result, contains("john", "tom", "jane"));
}
// ======================== Iterator
@Test
public void whenConvertIteratorToListUsingJava_thenSuccess() {
List<String> result = new ArrayList<String>();
while (iterator.hasNext()) {
result.add(iterator.next());
}
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToListUsingJava8_thenSuccess() {
List<String> result = new ArrayList<String>();
iterator.forEachRemaining(result::add);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToListUsingJava8WithSpliterator_thenSuccess() {
List<String> result = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
.collect(Collectors.toList());
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToListUsingGuava_thenSuccess() {
List<String> result = Lists.newArrayList(iterator);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToImmutableListUsingGuava_thenSuccess() {
List<String> result = ImmutableList.copyOf(iterator);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToListUsingApacheCommons_thenSuccess() {
List<String> result = IteratorUtils.toList(iterator);
assertThat(result, contains("john", "tom", "jane"));
}
}
@@ -0,0 +1,145 @@
package com.baeldung.java.collections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
@SuppressWarnings("unused")
public class JavaCollectionConversionUnitTest {
// List -> array; array -> List
@Test
public final void givenUsingCoreJava_whenArrayConvertedToList_thenCorrect() {
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
final List<Integer> targetList = Arrays.asList(sourceArray);
}
@Test
public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() {
final List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
final Integer[] targetArray = sourceList.toArray(new Integer[0]);
}
@Test
public final void givenUsingGuava_whenArrayConvertedToList_thenCorrect() {
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
final List<Integer> targetList = Lists.newArrayList(sourceArray);
}
@Test
public final void givenUsingGuava_whenListConvertedToArray_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final int[] targetArray = Ints.toArray(sourceList);
}
@Test
public final void givenUsingCommonsCollections_whenArrayConvertedToList_thenCorrect() {
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
final List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceArray);
}
// Set -> array; array -> Set
@Test
public final void givenUsingCoreJavaV1_whenArrayConvertedToSet_thenCorrect() {
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
final Set<Integer> targetSet = new HashSet<Integer>(Arrays.asList(sourceArray));
}
@Test
public final void givenUsingCoreJavaV2_whenArrayConvertedToSet_thenCorrect() {
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
final Set<Integer> targetSet = new HashSet<Integer>();
Collections.addAll(targetSet, sourceArray);
}
@Test
public final void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final Integer[] targetArray = sourceSet.toArray(new Integer[0]);
}
@Test
public final void givenUsingGuava_whenArrayConvertedToSet_thenCorrect() {
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
final Set<Integer> targetSet = Sets.newHashSet(sourceArray);
}
@Test
public final void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final int[] targetArray = Ints.toArray(sourceSet);
}
@Test
public final void givenUsingCommonsCollections_whenArrayConvertedToSet_thenCorrect() {
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
final Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceArray);
}
@Test
public final void givenUsingCommonsCollections_whenSetConvertedToArrayOfPrimitives_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final Integer[] targetArray = sourceSet.toArray(new Integer[0]);
final int[] primitiveTargetArray = ArrayUtils.toPrimitive(targetArray);
}
// Map (values) -> Array, List, Set
@Test
public final void givenUsingCoreJava_whenMapValuesConvertedToArray_thenCorrect() {
final Map<Integer, String> sourceMap = createMap();
final Collection<String> values = sourceMap.values();
final String[] targetArray = values.toArray(new String[0]);
}
@Test
public final void givenUsingCoreJava_whenMapValuesConvertedToList_thenCorrect() {
final Map<Integer, String> sourceMap = createMap();
final List<String> targetList = new ArrayList<>(sourceMap.values());
}
@Test
public final void givenUsingGuava_whenMapValuesConvertedToList_thenCorrect() {
final Map<Integer, String> sourceMap = createMap();
final List<String> targetList = Lists.newArrayList(sourceMap.values());
}
@Test
public final void givenUsingCoreJava_whenMapValuesConvertedToSet_thenCorrect() {
final Map<Integer, String> sourceMap = createMap();
final Set<String> targetSet = new HashSet<>(sourceMap.values());
}
// UTIL
private final Map<Integer, String> createMap() {
final Map<Integer, String> sourceMap = new HashMap<>(3);
sourceMap.put(0, "zero");
sourceMap.put(1, "one");
sourceMap.put(2, "two");
return sourceMap;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.java.lists;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
public class ListToStringUnitTest {
@Test
public void whenListToString_thenPrintDefault() {
List<Integer> intLIst = Arrays.asList(1, 2, 3);
System.out.println(intLIst);
}
@Test
public void whenCollectorsJoining_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(intList.stream()
.map(n -> String.valueOf(n))
.collect(Collectors.joining("-", "{", "}")));
}
@Test
public void whenStringUtilsJoin_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(StringUtils.join(intList, "|"));
}
}
@@ -0,0 +1,10 @@
### Relevant Articles:
- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys)
- [Using a Byte Array as Map Key in Java](https://www.baeldung.com/java-map-key-byte-array)
- [Using the Map.Entry Java Class](https://www.baeldung.com/java-map-entry)
- [Optimizing HashMaps Performance](https://www.baeldung.com/java-hashmap-optimize-performance)
- [Update the Value Associated With a Key in a HashMap](https://www.baeldung.com/java-hashmap-update-value-by-key)
- [Java Map keySet() vs. entrySet() vs. values() Methods](https://www.baeldung.com/java-map-entries-methods)
- [Java IdentityHashMap Class and Its Use Cases](https://www.baeldung.com/java-identityhashmap)
- [How to Invert a Map in Java](https://www.baeldung.com/java-invert-map)
@@ -0,0 +1,41 @@
<?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>java-collections-maps-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-collections-maps-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
</project>
@@ -0,0 +1,28 @@
package com.baeldung.map.bytearrays;
import java.util.Arrays;
public final class BytesKey {
private final byte[] array;
public BytesKey(byte[] array) {
this.array = array;
}
public byte[] getArray() {
return array.clone();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BytesKey bytesKey = (BytesKey) o;
return Arrays.equals(array, bytesKey.array);
}
@Override
public int hashCode() {
return Arrays.hashCode(array);
}
}
@@ -0,0 +1,35 @@
package com.baeldung.map.entry;
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
'}';
}
}
@@ -0,0 +1,34 @@
package com.baeldung.map.entry;
import java.util.HashMap;
import java.util.Map;
public class MapEntryEfficiencyExample {
public static void main(String[] args) {
MapEntryEfficiencyExample mapEntryEfficiencyExample = new MapEntryEfficiencyExample();
Map<String, String> map = new HashMap<>();
map.put("Robert C. Martin", "Clean Code");
map.put("Joshua Bloch", "Effective Java");
System.out.println("Iterating Using Map.KeySet - 2 operations");
mapEntryEfficiencyExample.usingKeySet(map);
System.out.println("Iterating Using Map.Entry - 1 operation");
mapEntryEfficiencyExample.usingEntrySet(map);
}
public void usingKeySet(Map<String, String> bookMap) {
for (String key : bookMap.keySet()) {
System.out.println("key: " + key + " value: " + bookMap.get(key));
}
}
public void usingEntrySet(Map<String, String> bookMap) {
for (Map.Entry<String, String> book: bookMap.entrySet()) {
System.out.println("key: " + book.getKey() + " value: " + book.getValue());
}
}
}
@@ -0,0 +1,25 @@
package com.baeldung.map.entry;
import java.util.*;
public class MapEntryTupleExample {
public static void main(String[] args) {
Map.Entry<String, Book> tuple1;
Map.Entry<String, Book> tuple2;
Map.Entry<String, Book> tuple3;
tuple1 = new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch"));
tuple2 = new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin"));
tuple3 = new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin"));
List<Map.Entry<String, Book>> orderedTuples = new ArrayList<>();
orderedTuples.add(tuple1);
orderedTuples.add(tuple2);
orderedTuples.add(tuple3);
for (Map.Entry<String, Book> tuple : orderedTuples) {
System.out.println("key: " + tuple.getKey() + " value: " + tuple.getValue());
}
}
}
@@ -0,0 +1,6 @@
package com.baeldung.map.hashing;
class Member {
Integer id;
String name;
}
@@ -0,0 +1,8 @@
package com.baeldung.map.hashing;
public class MemberWithBadHashing extends Member {
@Override
public int hashCode() {
return name.hashCode();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.map.hashing;
import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
public class MemberWithGuavaHashing extends Member {
@Override
public int hashCode() {
HashFunction hashFunction = Hashing.murmur3_32();
return hashFunction.newHasher()
.putInt(id)
.putString(name, Charsets.UTF_8)
.hash().hashCode();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.map.hashing;
public class MemberWithId extends Member {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithId that = (MemberWithId) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.map.hashing;
import java.util.Objects;
public class MemberWithIdAndName extends Member {
public static final int PRIME = 31;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithObjects that = (MemberWithObjects) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = PRIME * result + (name == null ? 0 : name.hashCode());
return result;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.map.hashing;
import java.util.Objects;
public class MemberWithObjects extends Member {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithObjects that = (MemberWithObjects) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
@@ -0,0 +1,156 @@
package com.baeldung.map.identity;
import java.util.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class IdentityHashMapDemonstrator {
public static void main(String[] args) {
IdentityHashMap<String, String> identityHashMap = createWithSimpleData();
System.out.println("Map details: " + identityHashMap);
IdentityHashMap<String, String> copiedMap = createFromAnotherMap(identityHashMap);
updateWithNewValue(copiedMap);
iterateIdentityHashMap(copiedMap);
addNullKeyValue();
demoHashMapVsIdentityMap();
demoMutableKeys();
Map<String, String> synchronizedMap = getSynchronizedMap();
//Do multithreaded operations on synchronizedMap
}
private static void addNullKeyValue() {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>();
identityHashMap.put(null, "Null Key Accepted");
identityHashMap.put("Null Value Accepted", null);
assertEquals("Null Key Accepted", identityHashMap.get(null));
assertEquals(null, identityHashMap.get("Null Value Accepted"));
}
private static void iterateIdentityHashMap(IdentityHashMap<String, String> identityHashMap) {
// Iterating using entrySet
System.out.println("Iterating values: ");
Set<Map.Entry<String, String>> entries = identityHashMap.entrySet();
for (Map.Entry<String, String> entry: entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Iterating using keySet
System.out.println("Iterating values using keySet: ");
for (String key: identityHashMap.keySet()) {
System.out.println(key + ": " + identityHashMap.get(key));
}
// Throws error if we modify while iterating
System.out.println("This iteration throws error: ");
try {
for (Map.Entry<String, String> entry: entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
identityHashMap.remove("title");
}
} catch (ConcurrentModificationException ex) {
System.out.println("This exception will raise for sure, if we modify while iterating");
}
}
private static class Book {
String title;
int year;
Book() {
// nothing to do
}
Book(String title, int year) {
this.title = title;
this.year = year;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return year == book.year && title.equals(book.title);
}
@Override
public int hashCode() {
return Objects.hash(title, year);
}
@Override
public String toString() {
return "Book{title='" + title + "', year=" + year + "}";
}
}
private static void demoMutableKeys() {
Book book1 = new Book("A Passage to India", 1924);
Book book2 = new Book("Invisible Man", 1953);
HashMap<Book, String> hashMap = new HashMap<>(10);
hashMap.put(book1, "A great work of fiction");
hashMap.put(book2, "won the US National Book Award");
book2.year = 1952;
assertEquals(null, hashMap.get(book2));
System.out.println("HashMap: " + hashMap);
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
identityHashMap.put(book1, "A great work of fiction");
identityHashMap.put(book2, "won the US National Book Award");
book2.year = 1951;
assertEquals("won the US National Book Award", identityHashMap.get(book2));
System.out.println("IdentityHashMap: " + identityHashMap);
}
private static void demoHashMapVsIdentityMap() {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>();
identityHashMap.put("title", "Harry Potter and the Goblet of Fire");
identityHashMap.put("author", "J. K. Rowling");
identityHashMap.put("language", "English");
identityHashMap.put("genre", "Fantasy");
HashMap<String, String> hashMap = new HashMap<>(identityHashMap);
hashMap.put(new String("genre"), "Drama");
assertEquals(4, hashMap.size());
System.out.println("HashMap content: " + hashMap);
identityHashMap.put(new String("genre"), "Drama");
assertEquals(5, identityHashMap.size());
System.out.println("IdentityHashMap content: " + identityHashMap);
}
private static Map<String, String> getSynchronizedMap() {
Map<String, String> synchronizedMap = Collections.synchronizedMap(new IdentityHashMap<String, String>());
return synchronizedMap;
}
private static IdentityHashMap<String, String> createFromAnotherMap(Map<String, String> otherMap) {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>(otherMap);
return identityHashMap;
}
private static void updateWithNewValue(IdentityHashMap<String, String> identityHashMap) {
String oldTitle = identityHashMap.put("title", "Harry Potter and the Deathly Hallows");
assertEquals("Harry Potter and the Goblet of Fire", oldTitle);
assertEquals("Harry Potter and the Deathly Hallows", identityHashMap.get("title"));
}
public static void addValue(IdentityHashMap<String, String> identityHashMap, String key, String value) {
identityHashMap.put(key, value);
}
public static void addAllValues(IdentityHashMap<String, String> identityHashMap, Map<String, String> otherMap) {
identityHashMap.putAll(otherMap);
}
public static IdentityHashMap<String, String> createWithSimpleData() {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>();
identityHashMap.put("title", "Harry Potter and the Goblet of Fire");
identityHashMap.put("author", "J. K. Rowling");
identityHashMap.put("language", "English");
identityHashMap.put("genre", "Fantasy");
return identityHashMap;
}
}
@@ -0,0 +1,59 @@
package com.baeldung.map.invert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class InvertHashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("first", 1);
map.put("second", 2);
System.out.println(map);
invertMapUsingForLoop(map);
invertMapUsingStreams(map);
invertMapUsingMapper(map);
map.put("two", 2);
invertMapUsingGroupingBy(map);
}
public static <V, K> Map<V, K> invertMapUsingForLoop(Map<K, V> map) {
Map<V, K> inversedMap = new HashMap<V, K>();
for (Entry<K, V> entry : map.entrySet()) {
inversedMap.put(entry.getValue(), entry.getKey());
}
System.out.println(inversedMap);
return inversedMap;
}
public static <V, K> Map<V, K> invertMapUsingStreams(Map<K, V> map) {
Map<V, K> inversedMap = map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey));
System.out.println(inversedMap);
return inversedMap;
}
public static <K, V> Map<V, K> invertMapUsingMapper(Map<K, V> sourceMap) {
Map<V, K> inversedMap = sourceMap.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue));
System.out.println(inversedMap);
return inversedMap;
}
public static <V, K> Map<V, List<K>> invertMapUsingGroupingBy(Map<K, V> map) {
Map<V, List<K>> inversedMap = map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
System.out.println(inversedMap);
return inversedMap;
}
}
@@ -0,0 +1,104 @@
package com.baeldung.map.bytearrays;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.Test;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class ByteArrayKeyUnitTest {
@Test
void givenPrimitiveByteArrayKey_whenRetrievingFromMap_shouldRetrieveDifferentObjects() {
// given
byte[] key1 = {1, 2, 3};
byte[] key2 = {1, 2, 3};
String value1 = "value1";
String value2 = "value2";
Map<byte[], String> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
// when
String retrievedValue1 = map.get(key1);
String retrievedValue2 = map.get(key2);
String retrievedValue3 = map.get(new byte[]{1, 2, 3});
// then
assertThat(retrievedValue1).isEqualTo(value1);
assertThat(retrievedValue2).isEqualTo(value2);
assertThat(retrievedValue3).isNull();
}
@Test
void givenEncodedStringKey_whenRetrievingFromMap_shouldRetrieveLastPutObject() {
// given
String key1 = Base64.getEncoder().encodeToString(new byte[]{1, 2, 3});
String key2 = Base64.getEncoder().encodeToString(new byte[]{1, 2, 3});
String value1 = "value1";
String value2 = "value2";
Map<String, String> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
// when
String retrievedValue1 = map.get(key1);
String retrievedValue2 = map.get(key2);
// then
assertThat(key1).isEqualTo(key2);
assertThat(retrievedValue1).isEqualTo(value2);
assertThat(retrievedValue2).isEqualTo(value2);
assertThat(retrievedValue1).isEqualTo(retrievedValue2);
}
@Test
void givenByteListKey_whenRetrievingFromMap_shouldRetrieveLastPutObject() {
// given
List<Byte> key1 = ImmutableList.of((byte)1, (byte)2, (byte)3);
List<Byte> key2 = ImmutableList.of((byte)1, (byte)2, (byte)3);
String value1 = "value1";
String value2 = "value2";
Map<List<Byte>, String> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
// when
String retrievedValue1 = map.get(key1);
String retrievedValue2 = map.get(key2);
// then
assertThat(key1).isEqualTo(key2);
assertThat(retrievedValue1).isEqualTo(value2);
assertThat(retrievedValue2).isEqualTo(value2);
assertThat(retrievedValue1).isEqualTo(retrievedValue2);
}
@Test
void givenCustomWrapperKey_whenRetrievingFromMap_shouldRetrieveLastPutObject() {
// given
BytesKey key1 = new BytesKey(new byte[]{1, 2, 3});
BytesKey key2 = new BytesKey(new byte[]{1, 2, 3});
String value1 = "value1";
String value2 = "value2";
Map<BytesKey, String> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
// when
String retrievedValue1 = map.get(key1);
String retrievedValue2 = map.get(key2);
String retrievedValue3 = map.get(new BytesKey(new byte[]{1, 2, 3}));
// then
assertThat(key1).isEqualTo(key2);
assertThat(retrievedValue1).isEqualTo(value2);
assertThat(retrievedValue2).isEqualTo(value2);
assertThat(retrievedValue1).isEqualTo(retrievedValue2);
assertThat(retrievedValue3).isEqualTo(value2);
}
}
@@ -0,0 +1,94 @@
package com.baeldung.map.caseinsensitivekeys;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.junit.Test;
import org.springframework.util.LinkedCaseInsensitiveMap;
import java.util.Map;
import java.util.TreeMap;
import static org.junit.Assert.*;
public class CaseInsensitiveMapUnitTest {
@Test
public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){
Map<String, Integer> treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("abc", 1);
treeMap.put("ABC", 2);
assertEquals(1, treeMap.size());
}
@Test
public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){
Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
commonsHashMap.put("abc", 1);
commonsHashMap.put("ABC", 2);
assertEquals(1, commonsHashMap.size());
}
@Test
public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 1);
linkedHashMap.put("ABC", 2);
assertEquals(1, linkedHashMap.size());
}
@Test
public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){
Map<String, Integer> treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("abc", 1);
treeMap.put("ABC", 2);
assertEquals(2, treeMap.get("aBc").intValue());
assertEquals(2, treeMap.get("ABc").intValue());
}
@Test
public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){
Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
commonsHashMap.put("abc", 1);
commonsHashMap.put("ABC", 2);
assertEquals(2, commonsHashMap.get("aBc").intValue());
assertEquals(2, commonsHashMap.get("ABc").intValue());
}
@Test
public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 1);
linkedHashMap.put("ABC", 2);
assertEquals(2, linkedHashMap.get("aBc").intValue());
assertEquals(2, linkedHashMap.get("ABc").intValue());
}
@Test
public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){
Map<String, Integer> treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("abc", 3);
treeMap.remove("aBC");
assertEquals(0, treeMap.size());
}
@Test
public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){
Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
commonsHashMap.put("abc", 3);
commonsHashMap.remove("aBC");
assertEquals(0, commonsHashMap.size());
}
@Test
public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 3);
linkedHashMap.remove("aBC");
assertEquals(0, linkedHashMap.size());
}
}
@@ -0,0 +1,33 @@
package com.baeldung.map.entry;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
public class MapEntryUnitTest {
@Test
public void givenSimpleEntryList_whenAddDuplicateKey_thenDoesNotOverwriteExistingKey() {
List<Map.Entry<String, Book>> orderedTuples = new ArrayList<>();
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch")));
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin")));
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin")));
assertEquals(3, orderedTuples.size());
assertEquals("9780134685991", orderedTuples.get(0).getKey());
assertEquals("9780132350884", orderedTuples.get(1).getKey());
assertEquals("9780132350884", orderedTuples.get(2).getKey());
}
@Test
public void givenRegularMap_whenAddDuplicateKey_thenOverwritesExistingKey() {
Map<String, Book> entries = new HashMap<>();
entries.put("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch"));
entries.put("9780132350884", new Book("Clean Code", "Robert C Martin"));
entries.put("9780132350884", new Book("Clean Code", "Robert C Martin"));
assertEquals(2, entries.size());
}
}
@@ -0,0 +1,126 @@
package com.baeldung.map.hashing;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class HashMapUpdateUnitTest {
Map<String, Double> fruitMap = new HashMap<>();
@BeforeAll
void setup() {
fruitMap.put("apple", 2.45);
fruitMap.put("grapes", 1.22);
}
@Test
public void givenFruitMap_whenPuttingAList_thenHashMapUpdatesAndInsertsValues() {
Double newValue = 2.11;
fruitMap.put("apple", newValue);
fruitMap.put("orange", newValue);
Assertions.assertEquals(newValue, fruitMap.get("apple"));
Assertions.assertTrue(fruitMap.containsKey("orange"));
Assertions.assertEquals(newValue, fruitMap.get("orange"));
}
@Test
public void givenFruitMap_whenKeyExists_thenValuesUpdated() {
double newValue = 2.31;
if (fruitMap.containsKey("apple")) {
fruitMap.put("apple", newValue);
}
Assertions.assertEquals(Double.valueOf(newValue), fruitMap.get("apple"));
}
@Test
public void givenFruitMap_whenReplacingOldValue_thenNewValueSet() {
double newPrice = 3.22;
Double applePrice = fruitMap.get("apple");
Double oldValue = fruitMap.replace("apple", newPrice);
Assertions.assertNotNull(oldValue);
Assertions.assertEquals(oldValue, applePrice);
Assertions.assertEquals(Double.valueOf(newPrice), fruitMap.get("apple"));
}
@Test
public void givenFruitMap_whenReplacingWithRealOldValue_thenNewValueSet() {
double newPrice = 3.22;
Double applePrice = fruitMap.get("apple");
boolean isUpdated = fruitMap.replace("apple", applePrice, newPrice);
Assertions.assertTrue(isUpdated);
}
@Test
public void givenFruitMap_whenReplacingWithWrongOldValue_thenNewValueNotSet() {
double newPrice = 3.22;
boolean isUpdated = fruitMap.replace("apple", Double.valueOf(0), newPrice);
Assertions.assertFalse(isUpdated);
}
@Test
public void givenFruitMap_whenGetOrDefaultUsedWithPut_thenNewEntriesAdded() {
fruitMap.put("plum", fruitMap.getOrDefault("plum", 2.41));
Assertions.assertTrue(fruitMap.containsKey("plum"));
Assertions.assertEquals(Double.valueOf(2.41), fruitMap.get("plum"));
}
@Test
public void givenFruitMap_whenPutIfAbsentUsed_thenNewEntriesAdded() {
double newValue = 1.78;
fruitMap.putIfAbsent("apple", newValue);
fruitMap.putIfAbsent("pear", newValue);
Assertions.assertTrue(fruitMap.containsKey("pear"));
Assertions.assertNotEquals(Double.valueOf(newValue), fruitMap.get("apple"));
Assertions.assertEquals(Double.valueOf(newValue), fruitMap.get("pear"));
}
@Test
public void givenFruitMap_whenComputeUsed_thenValueUpdated() {
double oldPrice = fruitMap.get("apple");
BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
fruitMap.compute(
"apple", (k, v) -> powFunction.apply(v, 2));
Assertions.assertEquals(
Double.valueOf(Math.pow(oldPrice, 2)), fruitMap.get("apple"));
Assertions.assertThrows(
NullPointerException.class, () -> fruitMap.compute("blueberry", (k, v) -> powFunction.apply(v, 2)));
}
@Test
public void givenFruitMap_whenComputeIfAbsentUsed_thenNewEntriesAdded() {
fruitMap.computeIfAbsent(
"lemon", k -> Double.valueOf(k.length()));
Assertions.assertTrue(fruitMap.containsKey("lemon"));
Assertions.assertEquals(Double.valueOf("lemon".length()), fruitMap.get("lemon"));
}
@Test
public void givenFruitMap_whenComputeIfPresentUsed_thenValuesUpdated() {
Double oldAppleValue = fruitMap.get("apple");
BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
fruitMap.computeIfPresent(
"apple", (k, v) -> powFunction.apply(v, 2));
Assertions.assertEquals(Double.valueOf(Math.pow(oldAppleValue, 2)), fruitMap.get("apple"));
}
@Test
public void givenFruitMap_whenMergeUsed_thenNewEntriesAdded() {
double defaultValue = 1.25;
BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
fruitMap.merge(
"apple", defaultValue, (k, v) -> powFunction.apply(v, 2));
fruitMap.merge(
"strawberry", defaultValue, (k, v) -> powFunction.apply(v, 2));
Assertions.assertTrue(fruitMap.containsKey("strawberry"));
Assertions.assertEquals(Double.valueOf(defaultValue), fruitMap.get("strawberry"));
Assertions.assertEquals(Double.valueOf(Math.pow(defaultValue, 2)), fruitMap.get("apple"));
}
}
@@ -0,0 +1,76 @@
package com.baeldung.map.hashing;
import com.google.common.base.Stopwatch;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.HashMap;
import java.util.SplittableRandom;
import java.util.function.Supplier;
public class HashingUnitTest {
public static final int SAMPLES = 1000000;
private SplittableRandom random = new SplittableRandom();
private String[] names = {"John", "Adam", "Suzie"};
@Test
void givenPrimitiveByteArrayKey_whenRetrievingFromMap_shouldRetrieveDifferentObjects() {
// bad hashing example is prohibitively slow for bigger samples
// Duration[] badHashing = testDuration(MemberWithBadHashing::new);
Duration[] withId = testDuration(MemberWithId::new);
Duration[] withObjects = testDuration(MemberWithObjects::new);
Duration[] withIdAndName = testDuration(MemberWithIdAndName::new);
// System.out.println("Inserting with bad hashing:");
// System.out.println(badHashing[0]);
// System.out.println("Getting with bad hashing:");
// System.out.println(badHashing[1]);
System.out.println("Inserting with id hashing:");
System.out.println(withId[0]);
System.out.println("Getting with id hashing:");
System.out.println(withId[1]);
System.out.println("Inserting with id and name hashing:");
System.out.println(withIdAndName[0]);
System.out.println("Getting with id and name hashing:");
System.out.println(withIdAndName[1]);
System.out.println("Inserting with Objects hashing:");
System.out.println(withObjects[0]);
System.out.println("Getting with Objects hashing:");
System.out.println(withObjects[1]);
}
private String randomName() {
return names[random.nextInt(2)];
}
private <T extends Member> Duration[] testDuration(Supplier<T> factory) {
HashMap<T, String> map = new HashMap<>();
Stopwatch stopwatch = Stopwatch.createUnstarted();
stopwatch.start();
for(int i = 0; i < SAMPLES; i++) {
T member = factory.get();
member.id = i;
member.name = randomName();
map.put(member, member.name);
}
stopwatch.stop();
Duration elapsedInserting = stopwatch.elapsed();
stopwatch.reset();
stopwatch.start();
for (T key : map.keySet()) {
map.get(key);
}
stopwatch.stop();
Duration elapsedGetting = stopwatch.elapsed();
stopwatch.reset();
return new Duration[]{elapsedInserting, elapsedGetting};
}
}
@@ -0,0 +1,21 @@
package com.baeldung.map.identity;
import org.junit.jupiter.api.Test;
import java.util.IdentityHashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class IdentityHashMapDemonstratorUnitTest {
@Test
public void givenIdentityHashMap_whenNewObjectWithSameKey_thenAddsAsNewValue() {
IdentityHashMap<String, String> identityHashMap = IdentityHashMapDemonstrator.createWithSimpleData();
String newGenreKey = new String("genre");
identityHashMap.put(newGenreKey, "Drama");
assertEquals(5, identityHashMap.size());
assertEquals("Fantasy", identityHashMap.get("genre"));
assertEquals("Drama", identityHashMap.get(newGenreKey));
}
}
@@ -0,0 +1,72 @@
package com.baeldung.map.invert;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class InvertHashMapUnitTest {
Map<String, Integer> sourceMap;
@BeforeEach
void setup() {
sourceMap = new HashMap<>();
sourceMap.put("Sunday", 0);
sourceMap.put("Monday", 1);
sourceMap.put("Tuesday", 2);
sourceMap.put("Wednesday", 3);
sourceMap.put("Thursday", 4);
sourceMap.put("Friday", 5);
sourceMap.put("Saturday", 6);
}
@Test
void givenSourceMap_whenUsingForLoop_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMap_whenUsingStreams_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMap_whenUsingMapper_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMapWithDuplicateValues_whenUsingGroupBy_returnsInvertedMap() {
sourceMap.put("MONDAY", 1);
Map<Integer, List<String>> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap);
assertNotNull(inversedMap);
assertNotEquals(sourceMap.size(), inversedMap.size()); // duplicate keys are merged now
assertEquals(2, inversedMap.get(1).size());
assertTrue(inversedMap.get(1).contains("Monday"));
assertTrue(inversedMap.get(1).contains("MONDAY"));
}
}
@@ -0,0 +1,30 @@
package com.baeldung.map.keysetValuesEntrySet;
import org.junit.Test;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EntrySetExampleUnitTest {
@Test
public void givenHashMap_whenEntrySetApplied_thenShouldReturnSetOfEntries() {
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
Set<Map.Entry<String, Integer>> actualValues = map.entrySet();
assertEquals(2, actualValues.size());
assertTrue(actualValues.contains(new SimpleEntry<>("one", 1)));
assertTrue(actualValues.contains(new SimpleEntry<>("two", 2)));
}
}
@@ -0,0 +1,27 @@
package com.baeldung.map.keysetValuesEntrySet;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class KeySetExampleUnitTest {
@Test
public void givenHashMap_whenKeySetApplied_thenShouldReturnSetOfKeys() {
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
Set<String> actualValues = map.keySet();
assertEquals(2, actualValues.size());
assertTrue(actualValues.contains("one"));
assertTrue(actualValues.contains("two"));
}
}
@@ -0,0 +1,27 @@
package com.baeldung.map.keysetValuesEntrySet;
import org.junit.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ValuesExampleUnitTest {
@Test
public void givenHashMap_whenValuesApplied_thenShouldReturnCollectionOfValues() {
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
Collection<Integer> actualValues = map.values();
assertEquals(2, actualValues.size());
assertTrue(actualValues.contains(1));
assertTrue(actualValues.contains(2));
}
}
+3
View File
@@ -117,6 +117,9 @@
<module>core-java-regex</module>
<module>core-java-regex-2</module>
<module>core-java-uuid</module>
<module>java-collections-conversions</module>
<module>java-collections-conversions-2</module>
<module>java-collections-maps-3</module>
<module>pre-jpms</module>
</modules>