簡體   English   中英

如何從 map 中的列表中獲取元素數?

[英]How do I get the number of elements from a list which is in a map?

到目前為止,我正在編寫學生管理程序,並希望按課程編號降序和升序對課程進行排序。

student.class 使用我存儲我的學生的列表。應該看起來像這樣。

    public class courses{
        Coursenumber coursenumber;
        int grade;
        Teacher teacher;
    
        List<Student> listOfStudentsInCourse = new ArrayList<>();
}

我將該列表放在 map 中,以便更輕松地訪問鍵值對。

TreeMap<Coursenumber, Course> showAllCoursesMap = new TreeMap<>();

        Course testCourse1 = new Klasse(
                new Coursenumber("XYZ"),
                grade 5,
                mrLee);

        Course testCourse1 = new Klasse(
                new Coursenumber("XYZ"),
                grade 5,
                mrSmith);

我使用 put 方法將它們都添加到 showAllCoursesMap 中。 output 應該是這樣的

testcourse1 number of students: 2
testcourse2 number of students: 1

您可以將 Stream API 用於 Java >= Java 8。基本上您想要做的是基於 Map 值的一些排序。 因此,我們使用 stream 和 map 使用Map.Entry.comparingByValue()根據值進行sorted和比較。 此方法采用一個Comparator ,我們可以使用Comparator.comparingInt()提供它。 然后我們只需要告訴comparingInt()我們想要比較的鍵是什么。 在您的情況下,這是列表的長度,因此您需要獲取列表及其大小。 最后但並非最不重要的一點是將結果收集在列表中。

如果您希望 List 以相反的順序排序,請添加Collections.reverseOrder()

這里有一個最小的例子,展示了你如何能做到這一點。 在我的例子中,結果將是List<Map.Entry<Integer, Application.Wrapper>>類型。 如果您只想要一個實際值的列表(在我的例子中是List<Application.Wrapper> ),您需要在toList()之前插入.map(Map.Entry::getValue) )

import java.util.*;

public class Application {
    public static void main(String[] args) {

        var test = new TreeMap<Integer, Wrapper>();
        test.put(1, new Wrapper(List.of(1, 2, 3, 4, 5, 6)));
        test.put(2, new Wrapper(List.of(1, 2, 3, 4)));
        test.put(3, new Wrapper(List.of(1, 2)));
        test.put(4, new Wrapper(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9)));

        // sort in ascending order (default)
        var resultAscending = test
                .entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Comparator.comparingInt(wrapper -> wrapper.getSomeList().size())))
                .toList();

        // sort in descending order
        var resultDescending = test
                .entrySet()
                .stream()
                // only change here: Collections.reverseOrder()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue(Comparator.comparingInt(wrapper -> wrapper.getSomeList().size()))))
                .toList();

        System.out.println(resultAscending);
        System.out.println(resultDescending);
    }


    static class Wrapper {
        List<Integer> someList;

        public Wrapper(List<Integer> someList) {
            this.someList = someList;
        }

        public List<Integer> getSomeList() {
            return someList;
        }

        @Override
        public String toString() {
            return someList + " (Size: %d)".formatted(someList.size());
        }
    }
}

預計 output

[3=[1, 2] (Size: 2), 2=[1, 2, 3, 4] (Size: 4), 1=[1, 2, 3, 4, 5, 6] (Size: 6), 4=[1, 2, 3, 4, 5, 6, 7, 8, 9] (Size: 9)]
[4=[1, 2, 3, 4, 5, 6, 7, 8, 9] (Size: 9), 1=[1, 2, 3, 4, 5, 6] (Size: 6), 2=[1, 2, 3, 4] (Size: 4), 3=[1, 2] (Size: 2)]

請注意: toString()方法使用從 Java 15 開始可用的formatted() ,因此如果您沒有使用String.format(" Size: (%d)", someList.size())而不是" (Size: %d)".formatted(someList.size())或完全刪除該格式,因為它僅在此處添加用於演示目的。

暫無
暫無

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

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