Hashmap sorting by value and assigning to a dto using java 8

Asked

Viewed 282 times

7

I currently have the following scenario functional:

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

I count the names repeated on List thus:

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

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

I order the return of Map counts in 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 how json works:

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

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

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

Minha Dto:

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

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

1 answer

6


Try to use the method map 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;

}
  • 1

    Hit the +1 vein.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.