I have a simple practice code where I have a simple list of Person objects.
What I wanted to do was to partition them based on their age being an even number of an odd number and then transform their names to upper case if they belonged to the even number group, names to lower case otherwise.
The difficulty I'm facing is performing this transformation using collect() operation.
Here's the simple person class
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@AllArgsConstructor
@Data
@Builder
@NoArgsConstructor
public class Person {
private String name;
private Gender gender;
private int age;
@Override
public String toString() {
return String.format("%s -- %s -- %d", name, gender, age);
}
}
And Here's a simple list of Person Objects
public static List<Person> getExpandedList() {
return Arrays.asList(new Person("Sara", Gender.FEMALE, 20), new Person("Sara", Gender.FEMALE, 22),
new Person("Bob", Gender.MALE, 20), new Person("Paula", Gender.FEMALE, 32),
new Person("Paul", Gender.MALE, 31), new Person("Jack", Gender.MALE, 2),
new Person("Jack", Gender.MALE, 72), new Person("Jill", Gender.FEMALE, 12),
new Person("Mahi", Gender.FEMALE, 11), new Person("Natalie", Gender.FEMALE, 3));
}
And the following is the code I was trying to use for the transformation.
So I want Mahi, Natalie, and Paul's name to appear in all lower case and rest of them should have names in all upper case and I want the entire person objects back, not just names.
Here's the code I was trying
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class PartitioningWithCollectors {
public static void main(String[] args) {
List<Person> personList = StreamsPracticeUtil.getExpandedList();
Map<Boolean, List<Person>> updatedPersons = personList.stream()
.collect(partitioningBy(person -> person.getAge() % 2 == 0,
//filtering(person -> person.getAge() % 2 == 0,
mapping(person -> Person.builder()
.age(person.getAge())
.gender(person.getGender())
.name(person.getName().toUpperCase())
.build(), toList())));//);
System.out.println(updatedPersons);
}
}
But of course, the problem is once I use any kind of filtering, the other result of the partitioning is gone.
In effect I want to perform the below operation in a functional way
for (Person person : personList) {
if (person.getAge() % 2 == 0) {
person.setName(person.getName().toUpperCase());
} else {
person.setName(person.getName().toLowerCase());
}
}
System.out.println(personList);
Appreciate any help I can get. Thanks..!!