[英]How to sort the list by fields in Java Spring Boot?
I relatively recently started teaching Spring and programming.我最近开始教授 Spring 和编程。 I try to sort the list by date, but I can't.
我尝试按日期对列表进行排序,但我不能。 I can't come to the right decision.
我无法做出正确的决定。 I will be very grateful for your help.
我将非常感谢您的帮助。
Is request:是要求:
> GET http://localhost:8080/expenses
How do I get a response like this:我如何得到这样的回应:
{
“2021-04-22”: [
{
“id”: 2,
“date”: “2021-04-22”,
“amount”: 12,
“currency”: “USD”,
“product”: “Salmon”
}
],
“2021-04-27”: [
{
“id”: 4,
“date”: “2021-04-27”,
“amount”: 4.75,
“currency”: “EUR”,
“product”: “Beer”
},
{
“id”: 5,
“date”: “2021-04-27”,
“amount”: 25.5,
“currency”: “UAH”,
“product”: “Sweets”
}
]
}
Here is my code:这是我的代码:
This is my class of Expense:这是我的 class 费用:
public class Expense {
private int id;
private static int idInc = 0;
private double amount;
private String currency;
private String product;
private String date;
public Expense() {
this.id = idInc++;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
This is my controller:这是我的 controller:
@RestController
public class ExpenseController {
@Autowired
private ExpenseService expenseService;
@RequestMapping("/expenses")
public Map<String, Object> all() {
return expenseService.getAllExpensesList();
}
@RequestMapping(method = RequestMethod.POST, value = "/expenses")
public void addExpense(@RequestBody Expense newExpense) {
expenseService.addExpense(newExpense);
}
}
This is my service:这是我的服务:
@Service
public class ExpenseService {
private Map<String, Object> map = new HashMap<>();
public Map<String, Object> getAllExpensesList(){
return map;
}
public void addExpense(Expense expense){
if(!map.containsKey(expense.getDate())) {
List<Expense> al = new ArrayList<>();
al.add(expense);
map.put(expense.getDate(), al);
}
else if(map.containsKey(expense.getDate())){
List<Expense> al = new ArrayList<>();
al.add(expense);
map.put(expense.getDate(), al);
}
}
}
How to do it right?怎么做才对? How to properly sort the list by date?
如何按日期正确排序列表?
Your class needs to implement Comparable interface, and You need to @Override the compare method in your class.您的 class 需要实现 Comparable 接口,并且您需要在 class 中 @Override 比较方法。 That should guide you to the right answer
这应该会引导你找到正确的答案
you should use the Comparable
interface and use Date
object instead of a string to represent the date.您应该使用
Comparable
接口并使用Date
object 而不是字符串来表示日期。
import java.time.LocalDate;
public class Expense implements Comparable<Expense> {
// all your fields
private LocalDate date; // instead of private String date;
// all getters and setters and constructor
@Override
public int compareTo(Expense e) {
if(this.date.isBefore(e))
return -1;
else if(this.date.isAfter(e))
return 1;
return 0;
}
}
while the date is String you can directly deal with compareTo
:虽然日期是 String 你可以直接处理
compareTo
:
if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0
and for instance, you can use a custom comparator:例如,您可以使用自定义比较器:
Collections.sort(list, (s1, s2) -> s1.getDate().compareTo(s2.getDate()) > 1 ? 1 : s1.getDate().compareTo(s2.getDate()) < 1 ? -1 : 0);
This has nothing to do with Spring.这与 Spring 无关。 This is a simple grouping by date string, and sort by date operations you are looking at.
这是按日期字符串进行的简单分组,并按您正在查看的日期操作进行排序。 Sorting can be achieved by using a TreeMap in which the keys are sorted.
排序可以通过使用对键进行排序的 TreeMap 来实现。
I have not compiled this code, so please bear with me if there are any syntax errors.我没有编译这段代码,所以如果有任何语法错误,请多多包涵。
Map<String,List<Expense>> resultMap = expenseList.stream().collect(Collectors.groupingBy(Expense::getDate, TreeMap::new, Collectors.toList());
The above code will give you the Map that you are expecting.上面的代码将为您提供您所期望的 Map。 You'll need to implement Comparable interface for TreeMap to sort the keys for you.
您需要为 TreeMap 实现 Comparable 接口来为您排序键。 Something like,
就像是,
@Override
public int compareTo(Expense o) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(this.date).compareTo(sdf.parse(o.getDate()));
} catch (Exception e) {
System.err.println(e.getMessage()); //Please handle it better!
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.