JAVA-12730: Rename java-collections-conversions-2 to
core-java-collections-conversions-2
This commit is contained in:
@@ -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()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user