Limit the size of Linkedhashmap

Asked

Viewed 97 times

0

I need to limit the output size of my Linkedhashmap:
It receives an undetermined number of information that needs to be reduced to no max 20 records: I put a limit on the function below, but I had no results.

Map <String, ReportLine> map = new LinkedHashMap();
                    skuOrderCount.entrySet().stream()
                            .sorted(Map.Entry.comparingByValue(Comparator.comparing(ReportLine::getTotalCount).reversed()))
                            .limit(20)
                            .forEach(entry -> {
                                map.put(entry.getKey(), entry.getValue());
                            });

Does anyone have any idea ?

1 answer

0


Instead of adding the values to an external map, you should use the stream output operations themselves.

In your case this will be solved by collecting the result of limit as follows:

Map<String, ReportLine> myNewMap = skuOrderCount.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.comparing(ReportLine::getTotalCount).reversed()))
                .limit(20).collect(Collectors.toMap(Entry::getKey, Entry::getValue));

You can check the terminal and intermediate operations at documentation

  • In reality the mistake was entirely mine, nor did I need to use its logic. My mistake was to insert in a foreach the instance of my linkedList, instead of the map shown above. But thank you very much ermão.abrrss

Browser other questions tagged

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