0

I have a sorted hashmap of projects acting as keys with values with a score for each project, the hashmap is sorted based on that score.

I need to display the key and value for each element of the hashmap in a Thymeleaf template and have attempted to do this but it hasn't worked as I expected.

Included below is the code from controller, service and template - though you will probably only need to look at the template.

The controller:

    @GetMapping("/admin-dashboard")
    private String getAdminDashboard(Model model){
        //Functionality that displays top 10 projects
        HashMap<Project, Long> sortedMap = adminService.getSuccessfulSortedProjects();
        model.addAttribute(sortedMap);

        return "admin-dashboard";
    }
    //Service Layer
    public HashMap<Project, Long> getSuccessfulSortedProjects() {
        List<Project> projectList = projectRepo.findAll();

        for (Project project:
                projectList) {
            System.out.println(project.getDescription());
        }

        HashMap<Project, Long> projectScoresHashMap = new HashMap<Project, Long>();


        //For each project in projectList get the amountContributed and sort Also date published

        for (Project project:
                projectList) {

            project.calculateAndSetProjectScore();
            System.out.println(project.getProjectScore());
            long projectScore = project.getProjectScore();

            projectScoresHashMap.put(project, projectScore);

        }
        //Sort hashmap:

        // Create a list from elements of HashMap
        List<Map.Entry<Project, Long> > list =
                new LinkedList<Map.Entry<Project, Long> >(projectScoresHashMap.entrySet());

        // Sort the list
        Collections.sort(list, new Comparator<Map.Entry<Project, Long> >() {
            public int compare(Map.Entry<Project, Long> o1,
                               Map.Entry<Project, Long> o2)
            {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });


        // put data from sorted list to hashmap
        HashMap<Project, Long> sortedMap = new LinkedHashMap<Project, Long>();

        int count = 0;

        for (Map.Entry<Project, Long> aa : list) {
            if (count < 10) {
                sortedMap.put(aa.getKey(), aa.getValue());
                System.out.println(aa.getKey() + " " + aa.getValue());
            }
            count++;
        }
        System.out.println("Sorted Map Elements: ");
        sortedMap.entrySet().forEach(entry -> {
            System.out.println(entry.getKey() + " " + entry.getValue());
        });


        return sortedMap;
    }

The template:

    <table>
        <thead>
        <tr>
            <th>#</th>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Age</th>
            <th>Created</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="entry, stats : ${sortedMap}" th:with="project=${entry.value}">
            <td th:text="${stats.index + 1}">1</td>
            <td th:text="${entry.key}">100</td>
            <td th:text="${project.url}">John</td>
            <td th:text="${project.amountContributed}">Doe</td>
            <td th:text="${project.targets}">john.doe@example.com</td>
            <td th:text="${project.projectScore}">27</td>
            <td th:text="${#dates.format(project.publishedOn, 'MMMM dd, yyyy')}">January 15, 2020</td>
        </tr>
        </tbody>
    </table>
andrewJames
  • 19,570
  • 8
  • 19
  • 51
devo9191
  • 219
  • 3
  • 13
  • 1
    Have you looked at the various approaches presented in the answers to [this question](https://stackoverflow.com/questions/23144358/how-to-loop-through-map-in-thymeleaf)? And probably other similar questions/answers also? If these did not help you, can you clarify why they did not help? – andrewJames Aug 14 '21 at 22:35
  • @andrewjames Because even when I copy and paste and change the variables exactly it doesn't work, for example I just tried the linked question and still nothing is displayed. – devo9191 Aug 14 '21 at 23:38
  • 1
    Ok - can you be more specific? what does "it doesn't work" mean? What exactly did you try? Nothing is displayed, but, for example, are there any errors? – andrewJames Aug 14 '21 at 23:54
  • @andrewjames No errors, map successfully prints to console so i know it is right. I tried keyvalue num – devo9191 Aug 15 '21 at 00:11
  • I don't think `model.addAttribute(sortedMap);` is creating a variable named `${sortedMap}` on the model (it's creating some other name). Why don't you specify the name? – Metroids Aug 15 '21 at 00:27
  • I see you are using `model.addAttribute(sortedMap);` - I have never used that method signature. I use `model.addAttribute("sortedMap", sortedMap);`, so that the object explicitly has the same name you use in the Thymeleaf template: `${sortedMap}`. – andrewJames Aug 15 '21 at 00:31

0 Answers0