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>