public class StreamSortTest {
@Data
@AllArgsConstructor
static class OrgAccountVo {
private String userId;
private String accountRole;
private Date joinTime;
}
public static void main(String[] args) {
List<OrgAccountVo> accountVoList = new ArrayList<>();
accountVoList.add(new OrgAccountVo("5","管理员", new Date()));
accountVoList.add(new OrgAccountVo("3","成员", new Date()));
accountVoList.add(new OrgAccountVo("1","成员", new Date()));
accountVoList.add(new OrgAccountVo("4","成员", new Date()));
accountVoList.add(new OrgAccountVo("2","成员", new Date()));
System.out.println("**************************排序前**************************");
accountVoList.stream().forEach(vo -> System.out.println(vo));
System.out.println("**************************按照userId排序**************************");
List<OrgAccountVo> sortedAccountVoList = accountVoList.stream().sorted(Comparator.comparing(OrgAccountVo::getUserId)).collect(Collectors.toList());
sortedAccountVoList.stream().forEach(vo -> System.out.println(vo));
System.out.println("**************************按照成员排序**************************");
List<OrgAccountVo> accountVoList1 = accountVoList.stream().sorted(Comparator.comparing(OrgAccountVo::getAccountRole)).collect(Collectors.toList());
accountVoList1.stream().forEach(vo -> System.out.println(vo));
System.out.println("**************************按照成员和时间排序**************************");
List<OrgAccountVo> accountVoList2 = accountVoList.stream().sorted(Comparator.comparing(OrgAccountVo::getAccountRole).reversed()
.thenComparing(OrgAccountVo::getJoinTime)).collect(Collectors.toList());
accountVoList2.stream().forEach(vo -> System.out.println(vo));
}
}
利用Stream给集合排序
最新推荐文章于 2024-07-13 17:43:31 发布