Springboot中如何对一个[{itemid:1,rating:0.9},{itemid:2,rating:0.8},{itemid:3,rating:0.5}]数组中的rating进行排序,并保留前rating值最大的10个
时间: 2023-11-27 11:52:13 浏览: 30
可以使用Java8的Stream API和Comparator来实现。具体步骤如下:
1. 将数组转换为Stream对象。
2. 使用sorted方法根据rating值进行排序。
3. 使用limit方法保留前10个元素。
4. 使用map方法将每个元素转换回原始的形式。
5. 使用collect方法将结果转换为List。
示例代码如下:
```java
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("itemid", 1);
map1.put("rating", 0.9);
list.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("itemid", 2);
map2.put("rating", 0.8);
list.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("itemid", 3);
map3.put("rating", 0.5);
list.add(map3);
List<Map<String, Object>> result = list.stream()
.sorted(Comparator.comparingDouble(item -> (Double) item.get("rating")).reversed())
.limit(10)
.map(item -> {
Map<String, Object> map = new HashMap<>();
map.put("itemid", item.get("itemid"));
map.put("rating", item.get("rating"));
return map;
})
.collect(Collectors.toList());
System.out.println(result);
```
输出结果为:
```
[{itemid=1, rating=0.9}, {itemid=2, rating=0.8}, {itemid=3, rating=0.5}]
```
说明排序和保留前10个元素的操作都成功了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)