简体   繁体   English

如何按 Java Spring Boot 中的字段对列表进行排序?

[英]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;
  }

如何自动格式化列表中的所有 bigdecimal 字段<object>带 spring 启动<div id="text_translate"><p>我的 Rest Api (由 Spring 引导)需要自动转换 ZA8Z6FDE6331BD59EB66AC 列表中的 BigDecimal 字段。</p><p> 前任:</p><pre> class EmployeeDTO { private String name; private BigDecimal salary; // 12345 --&gt; need to 12,345 } @PostMapping(path = "/get-list-employee") public ResponseEntity&lt;Object&gt; searchListEmployee(@RequestBody EmployeeDTO employeeDTO) throws JSONException { return new ResponseEntity&lt;Object&gt;(employeeService.searchListEmployee(employeeDTO).getBody(), HttpStatus.OK); }</pre><p> 并且需要每个员工有薪水的返回列表已经格式化。</p><p> 我找到了一些格式化方式,比如使用 PropertyEditorRegistrar 或 CustomNumberFormat,...</p><p> 但似乎,它不支持列表 object。</p><p> 有人告诉我如何格式化 object 列表中的所有 bigdecimal 字段吗?</p></div></object> - How to automatic fomat all bigdecimal fields in list <object> with spring boot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Spring 引导中对 List&lt;&gt; 中的月份进行排序 - 使用 Java 8 - How to sort months in List<> in Spring boot - Using Java 8 如何获得 java spring 引导中未列出的结果 - how to get the result not list in java spring boot 如何自动格式化列表中的所有 bigdecimal 字段<object>带 spring 启动<div id="text_translate"><p>我的 Rest Api (由 Spring 引导)需要自动转换 ZA8Z6FDE6331BD59EB66AC 列表中的 BigDecimal 字段。</p><p> 前任:</p><pre> class EmployeeDTO { private String name; private BigDecimal salary; // 12345 --&gt; need to 12,345 } @PostMapping(path = "/get-list-employee") public ResponseEntity&lt;Object&gt; searchListEmployee(@RequestBody EmployeeDTO employeeDTO) throws JSONException { return new ResponseEntity&lt;Object&gt;(employeeService.searchListEmployee(employeeDTO).getBody(), HttpStatus.OK); }</pre><p> 并且需要每个员工有薪水的返回列表已经格式化。</p><p> 我找到了一些格式化方式,比如使用 PropertyEditorRegistrar 或 CustomNumberFormat,...</p><p> 但似乎,它不支持列表 object。</p><p> 有人告诉我如何格式化 object 列表中的所有 bigdecimal 字段吗?</p></div></object> - How to automatic fomat all bigdecimal fields in list <object> with spring boot 如何根据java中的多个字段值对列表进行排序 - How to sort list based on multiple fields value in java Java Spring-boot:如何返回列表而不是单个结果? - Java Spring-boot: how to return a list and not a single result? 如何按Java中的两个字段排序? - How to sort by two fields in Java? 如何按 2 个字段对对象进行排序 Java - How to Sort objects by 2 fields Java 在 Java Spring Boot 中将列表转换为分组列表 - Convert List to grouped list in Java Spring Boot Java List对对象字段的常量值进行排序 - Java List sort on object fields constant values 在 java 中按多个字段排序列表(然后不比较) - Sort list by multiple fields(not then compare) in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM