簡體   English   中英

如何對地圖進行排序 <String, List<Summary> &gt;

[英]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;
}

我需要通過元素List的getFavorite_count對地圖mostMentionsMap進行排序,以返回已排序的地圖。 我已經在對每個地圖項的元素進行排序,但是我需要對地圖使用相同的排序標准。

我可以按鍵排序查看代碼。

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));

但是,我必須按值元素的屬性排序(List)。 我不知道我講得好嗎?

好了,從您的問題中很明顯,您想按值對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
        ));

現在,尚不清楚(這就是Slaw的評論所要表達的)您希望如何對值進行排序(即valueComparator應該是什么)。 我們知道你想使用排序Summary::getFavorite_count ,但因為你有一個ListSummary “IES,選項有多個。 以下是其中一些選項:

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();

通常,當需要Java中特定的地圖排序時,您可能應該使用TreeMap。 現在,我假設.getFavorite_count返回一個int,因此該鍵將必須為Integer類型,因為我不確定使String類型的鍵是否會像您當前在返回類型中那樣對String類型的數字進行排序。

您可以使用可比接口:

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;
    }

}

您可以在此處了解更多信息。 它也應該與地圖一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM