一、定义dto
package test.bestfei.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class PremierLeagueTable {
@ApiModelProperty("rank")
private int rank;
@ApiModelProperty("team")
private String team;
@ApiModelProperty("points")
private int points;
}
二、代码实现
转成List,并按rank字段排序
package test.futures.bestfei;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.util.stream.Collectors;
import test.bestfei.dto.PremierLeagueTable;
@Test
public void testStringToJsonList(){
String s = "[{\"rank\":1,\"team\":\"Liverpool\",\"points\":100}," +
"{\"rank\":2,\"team\":\"Arsenal\",\"points\":98},\n" +
"{\"rank\":4,\"team\":\"Chelsea\",\"points\":90},\n" +
"{\"rank\":3,\"team\":\"Manchester Utd\",\"points\":97}]";
List<PremierLeagueTable> ranks = JSON.parseObject(s, new TypeReference<List<PremierLeagueTable>>() {
});
System.out.println("sort rank");
ranks = ranks.stream().sorted(Comparator.comparing(PremierLeagueTable::getRank)).collect(Collectors.toList());
for(int i=0;i<ranks.size();i++){
System.out.println("rank:"+ranks.get(i).getRank()+",team:"+ranks.get(i).getTeam()+",points:"+ranks.get(i).getPoints());
}
System.out.println("sort reversed rank");
ranks = ranks.stream().sorted(Comparator.comparing(PremierLeagueTable::getRank).reversed()).collect(Collectors.toList());
for(int i=0;i<ranks.size();i++){
System.out.println("rank:"+ranks.get(i).getRank()+",team:"+ranks.get(i).getTeam()+",points:"+ranks.get(i).getPoints());
}
System.out.println("sort points");
ranks = ranks.stream().sorted(Comparator.comparing(PremierLeagueTable::getPoints)).collect(Collectors.toList());
for(int i=0;i<ranks.size();i++){
System.out.println("rank:"+ranks.get(i).getRank()+",team:"+ranks.get(i).getTeam()+",points:"+ranks.get(i).getPoints());
}
}
网友评论