Home > database >  Java streams Map to Dto in Map<String,List> by specific attribute in Java 8
Java streams Map to Dto in Map<String,List> by specific attribute in Java 8

Time:11-22

I want to get the list after using stream and then mapping person object to its dto.

I kept the "VALUE" as a enum like VALUE1, VALUE2, VALUE3. Here is my values in Map<String (id), List<Person>>

Id, Tag, Value, Date , Message
p1, VALUE1, 10, 10-10-2000 , "Message"
p2, VALUE1, 20, 10-10-2000 , "Message"
p1, VALUE2, "Text", 10-10-2000 , "Message"
p2, VALUE2, "Text", 10-10-2000 , "Message"
p1, VALUE3, 11-11-2000, 10-10-2000 , "Message"
p2, VALUE3, 12-11-2000, 10-10-2000 , "Message"

What I want to get this result shown below.

Tag, Id, Value, Date
VALUE1, p1, 10, "10-10-2000"
VALUE1, p2, 20, "10-10-2000"  
VALUE2, p1, "Text", "10-10-2000"  
VALUE2, p2, "Text", "10-10-2000"  
VALUE3, p1, 11-11-2000, "10-10-2000"  
VALUE3, p2, 12-11-2000, "10-10-2000"

As you can see, Value column has different values (String, Int, Date). That's why I defined value as a object. I also store the date as a localdate.

Here is my Value class shown below.

public enum Value {
    VALUE1,VALUE2,VALUE3
}

Here is my Dto class shown below.

public class PersonDto {
    private Value value;
    private String id;
    private String date;
    private Object result;
}
 

How can I do that?

Here is my code snippets shown below. However, I cannot continue

static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");

    List<PersonDto > result= persons.values().stream()
            .flatMap(List::stream).map(person->
                    String date = LocalDate.parse(person.getEventDate(), formatter) // Error
                    new PersonDto (person.getEvent(),person.getEmpID(),
                            ,person.getEvent())
            .collect(Collectors.toList());..

CodePudding user response:

Here is the answer shown below

List<PersonDto> yearlyFinancialReportDtos = persons.values().stream()
                .flatMap(List::stream).map(person ->
                        new YearlyFinancialReportDto(person.getValue(),person .getId(),formatter.format(person .getDate())
                                ,person .getResult()))
                .collect(Collectors.toList());
  • Related