spring boot 的分类统计接口怎么写有衣服 游戏 实物 球四个字段
以下是一个示例的Spring Boot的分类统计接口,包含了衣服、游戏、实物、球四个字段:
@RestController
@RequestMapping("/statistics")
public class StatisticsController {
@Autowired
private ProductService productService;
@GetMapping("/category")
public Map<String, Integer> getCategoryStatistics() {
Map<String, Integer> result = new HashMap<>();
List<Product> products = productService.getAllProducts(); // 获取所有商品
int clothesCount = 0;
int gameCount = 0;
int goodsCount = 0;
int ballCount = 0;
// 遍历所有商品,统计分类数量
for (Product product : products) {
if (product.getCategory().equals("衣服")) {
clothesCount++;
} else if (product.getCategory().equals("游戏")) {
gameCount++;
} else if (product.getCategory().equals("实物")) {
goodsCount++;
} else if (product.getCategory().equals("球")) {
ballCount++;
}
}
// 将统计结果放入Map中返回
result.put("衣服", clothesCount);
result.put("游戏", gameCount);
result.put("实物", goodsCount);
result.put("球", ballCount);
return result;
}
}
在这个示例中,我们定义了一个 /statistics/category 的接口,用于统计不同分类的商品数量。首先,我们在 StatisticsController 中注入了 ProductService,用于获取所有的商品数据。然后,在接口实现中,我们遍历了所有的商品,根据不同分类统计数量,并将结果放入一个 Map 中返回。最终,我们返回的结果会形如:
{
"衣服": 10,
"游戏": 5,
"实物": 8,
"球": 3
}
表示衣服有10件、游戏有5个、实物有8个、球有3个。
原文地址: http://www.cveoy.top/t/topic/bLBl 著作权归作者所有。请勿转载和采集!