如何对地图进行排序<String, List<Summary>>

How to Sort Map<String, List<Summary>>

我需要按列表值元素的属性对地图进行排序。见代码。

public Map<String, List<Summary>> getMostMentions() throws Exception {

    List<Tweet> tweets;
    try {
        tweets = getApiFromTweet().getTweets();
    } catch (Exception e) {
        throw new Exception(e);
    }


    List<Summary> summary = new ArrayList<>();

    tweets.forEach(t -> {
        summary.add(
                new Summary(
                        t.getUser().getScreen_name(), 
                        t.getFollowersCount(), 
                        t.getRetweet_count(),                   
                        t.getFavorite_count(), 
                        t.getText(), 
                        t.getCreated_at(),
                        appConfig.getProfileLink(t.getUser().getScreen_name()),
                        appConfig.getTweetLink(t.getUser().getScreen_name(), t.getId())));
    });

    Map<String, List<Summary>> mostMentionsMap = summary.stream().collect(Collectors.groupingBy(Summary::getScreen_name));

    mostMentionsMap.forEach((k,v) -> {
        v.sort(Comparator.comparing(Summary::getFavorite_count).reversed());
    });


    return mostMentionsMap;
}

I need sort the map mostMentionsMap by getFavorite_count of the elements List to return map sorted. I'm already sorting the elements of each map item, but I need to use the same sorting criteria for the map.

我可以按键排序看代码。

LinkedHashMap<String, List<SummaryTweet>> mapSorted = mostMentionsMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())             
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

但是,我必须按值(列表)的元素的属性进行排序。 不知道我解释的好不好?

一般来说,如果想要在 Java 中对地图进行特定排序,您可能应该使用 TreeMap。现在,我假设 .getFavorite_count returns 是一个 int 所以键需要是 Integer 类型,因为我不确定使 String 类型的键会像你目前拥有的那样对一些 String 类型进行排序在你的 return 类型中。

您可以使用比较接口:

public class YourNameOfTheClass implements Comparable</*Your objects, which should be sorted. Example: Car*/> {

/*Your code and stuff…*/

    @Override
    public int compareTo(/*Your object, which you wrote above and the name of it. Example: Car myCar*/) {

        /*
        Now here you should enter your criteria.

        If you want to sort something it should be comparable.

        Usually, this method returns '0', when the two objects, which are compared are equal. So you should write something like this:

        if (this.getFavourite() == car.getFavourite())
            return 0;

        This method returns a negative integer when the first object has a 'smaller' value and a positive integer when it's of greater value.

        Example:
        myCar.compareTo(yourCar) would return 0, if we're actually driving the same car. -1 when my Car is not as good as yours and +1 when my Car is better.
        */
    }
}

定义比较标准后,您可以像这样简单地对其进行排序:

Collections.sort(/*The name of your list*/)

我来演示一下:

public class CompareCars implements Comparable<Car> {

    public static void main (String [] args) {
        List<Car> allCars = new ArrayList<Car>();
        Collections.sort(allCars);
    }

    @Override
    public int compareTo (Car secondCar) {
        if (this.getLicensePlate() == secondCar.getLicensePlate() || this.getHP() == secondCar.getHP())
            return 0;
        if (this.getHP() > secondCar.getHP())
            return 1;
        else
            return -1;
    }

}

您可以阅读更多相关信息 here。它也应该适用于地图。

好吧,从你的问题中可以清楚地看出你想按值对 Map 进行排序。您可以使用:

Comparator<List<Summary>> valueComparator;

LinkedHashMap<String, List<Summary>> mapSorted = mostMentionsMap.entrySet().stream()
        .sorted(Map.Entry.comparingByValue(valueComparator))
        .collect(Collectors.toMap(
                Map.Entry::getKey, Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, // or throw here (just in case)
                LinkedHashMap::new
        ));

现在,还不清楚(这就是 的意思) 你想如何对值进行排序(即 valueComparator 应该是什么) .我们知道您想使用 Summary::getFavorite_count 进行排序,但由于您有 ListSummary 的排序,因此选项有多个。以下是其中的一些选项:

1) 按最大值排序:

// assumes Summaries are sorted by: Comparator.comparing(Summary::getFavorite_count).reversed()
Comparator.<List<Summary>>comparingInt(list -> list.isEmpty()
        ? 0
        : list.get(0).getFavorite_count()
).reversed();

2) 按总数排序:

Comparator.<List<Summary>>comparingInt(list -> list.stream()
        .mapToInt(Summary::getFavorite_count)
        .sum()
).reversed();

3)平均排序:

Comparator.<List<Summary>>comparingDouble(list -> list.stream()
        .mapToInt(Summary::getFavorite_count)
        .average().orElse(0)
).reversed();