Sorting HashMap by value and assigning a value using java 8

6

I currently have the following functional scenario:

A list of the Studios class with id and name: List<Studios> studios;

I count repeated names in List as follows:

Map<String, Integer> counts = new HashMap<>();
studios.forEach(studio -> counts.merge(studio.getName(), 1, Integer::sum));

No Map<String, Integer> counts has as key the name and as value the total of repetition found in List studios : Key = "Xpto", value = 5 .

I order the return of Map counts this way:

result = counts.entrySet().stream()
    .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
        (e1, e2) -> e2, LinkedHashMap::new));

Getting the json results:

{
    "Studio1": 6,
    "Studio3": 5,
    "Studio2": 4
}

My need is to pass a dto at the time of ordering to get the json return as follows:

{
  "studios": [
    {
        "name": "Studio 1",
        "cout": 6
    },
    {
        "name": "Studio 2",
        "count": 5
    }
  ]
}

My Dto:

public class Dto {
    private String studioName;
    private Integer count;
}

Note: Open to suggestions on how to improve the code are welcome.

    
asked by anonymous 21.09.2018 / 14:41

1 answer

5

Try using the map method of Stream and create a constructor or something to initialize the Dto class, as shown below:

Map<String, Integer> counts = new HashMap<>();
studios.forEach(studio -> counts.merge(studio, 1, Integer::sum));

List<Dto> lista = counts.entrySet().stream()
        .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
        .map(item -> new Dto(item.getKey(), item.getValue()))
        .collect(Collectors.toList());


public class Dto {
    public Dto(String studioName, Integer count) {
        this.studioName = studioName;
        this.count = count;
    }

    private String studioName;
    private Integer count;

}
    
21.09.2018 / 15:33