简体   繁体   中英

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

I'm programming a student administration so far and want to sort courses by their number descending and ascending.

The student.class wields a list which I store my students in. Should look like this.

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

And I'm putting that list in a map for easier access to the key-value pairs.

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

I added both of them in the showAllCoursesMap by using the put-method. The output should look like

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

You can use the Stream API for Java >= Java 8. Essentially what you want to do is some sorting based on Map values. Therefore we stream the map using sorted and compare based on the value using Map.Entry.comparingByValue() . This method takes a Comparator which we can provide by using Comparator.comparingInt() . We then only have to tell comparingInt() what the key is we want to compare on. In your case that's the length of the List so you need to get the list and its size. Last but not least collect the results in a list.

If you want the List sorted in reversed order add Collections.reverseOrder() .

Here a minimal example that shows how you can could do it. The result will be of type List<Map.Entry<Integer, Application.Wrapper>> in my case. If you just want a list of the actual values ( List<Application.Wrapper> in my case) you need to insert .map(Map.Entry::getValue) before toList()

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

Expected 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)]

Please note: The toString() method uses formatted() which is available starting from Java 15, so if you do not have that use String.format(" Size: (%d)", someList.size()) instead of " (Size: %d)".formatted(someList.size()) or drop that formatting completely as it was only added for demo purposes here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM