Spring Boot 分类统计接口开发指南:示例与代码
这个问题的答案取决于您的需求和数据结构。以下是一个示例实现,假设数据结构如下:
public class Item {
private String name;
private String category;
private int quantity;
// getters and setters
}
您可以编写一个REST API控制器来处理分类统计请求:
@RestController
@RequestMapping("/items")
public class ItemController {
private List<Item> items = new ArrayList<>();
@PostMapping("/")
public void addItem(@RequestBody Item item) {
items.add(item);
}
@GetMapping("/categories")
public Map<String, Integer> getCategoryCounts() {
Map<String, Integer> categoryCounts = new HashMap<>();
for (Item item : items) {
String category = item.getCategory();
if (categoryCounts.containsKey(category)) {
int count = categoryCounts.get(category);
categoryCounts.put(category, count + item.getQuantity());
} else {
categoryCounts.put(category, item.getQuantity());
}
}
return categoryCounts;
}
}
在这个示例中,我们使用@PostMapping来添加新项目,并使用@GetMapping来返回分类计数。我们遍历items列表并使用Map来存储每个类别的计数。如果类别已经存在于categoryCounts中,我们将项目的数量添加到当前计数中。否则,我们将新的类别和数量添加到categoryCounts中。最后,我们返回categoryCounts映射。
原文地址: https://www.cveoy.top/t/topic/ndwY 著作权归作者所有。请勿转载和采集!