java 排序


根据likedCount进行降序排序,截取前十条


回答:

根据你的demo模拟了一段代码
1.dto类

import lombok.Data;

/**

* @description:

* @class: InfoDTO

* @author: Yiang37

* @date: 2022/1/7 9:21

* @version: 1.0

*/

@Data

public class InfoDTO {

private String name;

private int age;

}

2.排序类

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.TypeReference;

import java.util.Comparator;

import java.util.List;

import java.util.stream.Collectors;

/**

* @description:

* @class: Parse

* @author: Yiang37

* @date: 2022/1/7 9:21

* @version: 1.0

*/

public class Parse {

public static void main(String[] args) {

String in = "[{\"name\":\"yang\",\"age\":120},{\"name\":\"wang\",\"age\":3},{\"name\":\"zhao\",\"age\":16},{\"name\":\"qian\",\"age\":18},{\"name\":\"sun\",\"age\":25},{\"name\":\"li\",\"age\":19},{\"name\":\"feng\",\"age\":10}]";

// 解析json

List<InfoDTO> infoDTOList = JSON.parseObject(in, new TypeReference<List<InfoDTO>>() {

});

// 源数据

infoDTOList.forEach(e -> System.out.println(e.getAge() + " - " + e.getName()));

System.out.println("-----------------------------------");

// 排序

List<InfoDTO> collect = infoDTOList.stream().sorted(Comparator.comparing(InfoDTO::getAge)).collect(Collectors.toList());

collect.forEach(e -> System.out.println(e.getAge() + " - " + e.getName()));

System.out.println("-----------------------------------");

// 排序 反转

List<InfoDTO> collect2 = infoDTOList.stream().sorted(Comparator.comparing(InfoDTO::getAge).reversed()).collect(Collectors.toList());

collect2.forEach(e -> System.out.println(e.getAge() + " - " + e.getName()));

System.out.println("-----------------------------------");

// 截取

List<InfoDTO> resList = collect.subList(0, 3);

resList.forEach(e -> System.out.println(e.getAge() + " - " + e.getName()));

}

}

3.程序输出

120 - yang

3 - wang

16 - zhao

18 - qian

25 - sun

19 - li

10 - feng

-----------------------------------

3 - wang

10 - feng

16 - zhao

18 - qian

19 - li

25 - sun

120 - yang

-----------------------------------

120 - yang

25 - sun

19 - li

18 - qian

16 - zhao

10 - feng

3 - wang

-----------------------------------

3 - wang

10 - feng

16 - zhao


回答:

如果是Java排序就对象实现Comparable 利用compareTo进行降序,截取前十条直接用subList取前十条就行了

以上是 java 排序 的全部内容, 来源链接: utcz.com/p/944157.html

回到顶部