首页 > 基础资料 博客日记
Java List集合去重、过滤、分组、获取数据、求最值、合并、排序、跳数据和遍历
2024-04-11 10:00:09基础资料围观235次
这篇文章介绍了Java List集合去重、过滤、分组、获取数据、求最值、合并、排序、跳数据和遍历,分享给大家做个参考,收藏Java资料网收获更多编程知识
前言
请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i、
准备工作:现有一个User类、Student 类和Ticket类,加入相关依赖
@Data
public class User {
/**
* id
*/
private Integer id;
/**
* 姓名
*/
private String name;
/**
* 工号
*/
private String jobNumber;
/**
* 年龄
*/
private Integer age;
/**
* true:男 false:女
*/
private Boolean gender;
/**
* 身高
*/
private Double height;
/**
* 出生日期
*/
private LocalDate birthday;
/**
* 成员数量
*/
private BigDecimal familyMemberQuantity;
public User(String name, String jobNumber, Integer age, Boolean gender, Double height, LocalDate birthday){
this.name = name;
this.jobNumber = jobNumber;
this.gender = gender;
this.age = age;
this.height = height;
this.birthday = birthday;
}
public User(String name,Integer age,BigDecimal familyMemberQuantity){
this.name = name;
this.age = age;
this.familyMemberQuantity = familyMemberQuantity;
}
/**
* 输出打印信息
* @param list
*/
public static void printUsers(List<User> list){
System.out.println("[姓名]\t\t[工号]\t\t[性别]\t\t[年龄]\t\t[身高]\t\t[生日]");
System.out.println("-----------------------------------------------------------------------");
list.forEach(u-> System.out.println(printValue(u)));
System.out.println(" ");
}
/***
* 输出list结果集
* @param user
* @return
*/
public static String printValue(User user){
String str=String.format("%s\t\t\t%s\t\t%s\t\t%s\t\t\t%s\t\t%s",
user.name,user.jobNumber,user.gender.toString(),user.age.toString(),
user.height.toString(),user.birthday.toString());
return str;
}
}
@Data
public class Ticket {
private String groupId;
private String mallid;
private String ticketId;
private String ticketName;
private String batchId;
private String convertible;
private String gradeLimit;
private String batchAvailableNum;
private String saleNum;
private String exIntegral;
private String exMoney;
private String isSoldOut;
private String isSpike;
private Date exEndTime;
private Date createDate;
/**
* 输出打印信息
* @param list
*/
public static void printTickets(List<Ticket> list){
System.out.println("[电子券名称]\t\t[isSoldOut]\t\t[convertible]\t\t[isSpike]\t\t[saleNum]\t\t[exIntegral]\t\t[exMoney]\t\t[exEndTime]\t\t[createDate]");
System.out.println("-----------------------------------------------------------------------");
list.forEach(u-> System.out.println(printValue(u)));
System.out.println(" ");
}
/***
* 输出list结果集
* @param ticket
* @return
*/
public static String printValue(Ticket ticket){
String str=String.format("%s\t\t\t\t%s\t\t\t\t%s\t\t\t\t\t%s\t\t\t\t%s\t\t\t%s\t\t\t%s\t\t\t%s\t\t\t%s",
ticket.ticketName,ticket.isSoldOut,ticket.convertible.toString(),ticket.isSpike.toString(),ticket.saleNum.toString(),
ticket.exIntegral.toString(),ticket.exMoney.toString(),ticket.exEndTime.toString(),ticket.createDate.toString());
return str;
}
}
@Data
public class Student {
private String id;
private int nums;
private int sums;
}
<!--Json工具类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
1. List集合去重:使用distinct()函数
使用stream().map()提取List对象的某一列值及去重
public class ListDistinct {
public static void main(String[] args) {
//构建测试数据
List<User> list = new ArrayList<User>();
list.add(new User("张三","000001",26,true,1.76, LocalDate.of(1996,1,18)));
list.add(new User("小莉","000002",21,false,1.61, LocalDate.of(2001,1,18)));
list.add(new User("李四","000003",22,true,1.83, LocalDate.of(2000,1,18)));
list.add(new User("程曦","000004",20,false,1.64, LocalDate.of(2002,1,18)));
list.add(new User("喜喜","000005",20,false,1.67, LocalDate.of(2002,1,18)));
//输出list列表
User.printUsers(list);
//1.提取某一列
List<String> nameList = list.stream().map(User::getName).collect(Collectors.toList());
System.out.println(JSON.toJSONString(nameList));
System.out.println("#############################################################");
//2.从列表中提取age并去重
List<Integer> ageList = list.stream().map(User::getAge).distinct().collect(Collectors.toList());
System.out.println(JSON.toJSONString(ageList));
System.out.println();
}
}
2.List集合过滤:使用filter方法可以过滤某些条件
public class ListFilter {
public static void main(String[] args) {
//构建测试数据
List<User> list = new ArrayList<>();
list.add(new User("张三","000001",26,true,1.76, LocalDate.of(1996,1,18)));
list.add(new User("小莉","000002",21,false,1.61, LocalDate.of(2001,1,18)));
list.add(new User("李四","000003",22,true,1.83, LocalDate.of(2000,1,18)));
list.add(new User("程曦","000004",20,false,1.64, LocalDate.of(2002,1,18)));
list.add(new User("喜喜","000005",20,false,1.67, LocalDate.of(2002,1,18)));
//输出list列表
User.printUsers(list);
//示例3:使用filter()过滤list
//查找身高在1.8米及以上的男生
List<User> teacherList = list.stream().filter(user -> user.getGender()
&& user.getHeight() >= 1.8).collect(Collectors.toList());
//输出查找结果
User.printUsers(teacherList);
//查找年龄在20以上的女生
List<User> tList = list.stream().filter(user -> !user.getGender()
&& user.getAge() >= 20).collect(Collectors.toList());
//输出查找结果
User.printUsers(tList);
}
}
3.List集合获取第一条数据
使用 findAny() 和 findFirst() 获取第一条数据
public class ListFindAnyFindFirst {
public static void main(String[] args) {
//构建测试数据
List<User> list = new ArrayList<User>();
list.add(new User("张丹",11,new BigDecimal(11)));
list.add(new User("刘大",13,new BigDecimal(13)));
list.add(new User("飒飒",16,new BigDecimal(16)));
list.add(new User("斯蒂芬",11,new BigDecimal(11)));
//1. findAny():将返回集合中符合条件的任意一个元素。
//findAny()Java Stream的方法为该流的某些元素返回一个Optional,如果该流为空,则返回一个空的Optional。在这里,Optional是一个容器对象,可以包含也可以不包含非null值
Optional<User> userOptional = list.stream().findAny();
System.out.println(userOptional.get());
//1. findFirst():获取第一条数据
//如果一个集合数据是有序的,而且你要查找符合条件的第一条数据。这时用findFirst是比较合适的
Optional<User> userOptional1 = list.stream().findFirst();
System.out.println(userOptional1.get());
/***
* 问题解答:findFirst和findAny如何选择?
* (1)如果你不关心返回的是哪一个数据,只要符合条件的就行,那就用findAny。
* 而且在并行流上,findAny限制更少。
* (2)如果你关心集合的顺序,要返回符合条件的第一个元素,那就用findFirst。
*/
}
}
4.List集合分组:通过Collectors.groupingBy可以分组指定字段
public class ListGrouping {
public static void main(String[] args) {
//构建测试数据
List<User> list = new ArrayList<>();
list.add(new User("张三","000001",26,true,1.76, LocalDate.of(1996,1,18)));
list.add(new User("小莉","000002",21,false,1.61, LocalDate.of(2001,1,18)));
list.add(new User("李四","000003",22,true,1.83, LocalDate.of(2000,1,18)));
list.add(new User("程曦","000004",20,false,1.64, LocalDate.of(2002,1,18)));
list.add(new User("喜喜","000005",20,false,1.67, LocalDate.of(2002,1,18)));
//输出list列表
User.printUsers(list);
//示例2:list分组(通过groupingBy可以分组指定字段)
System.out.println("###############################单字段分组##############################");
//2.1单字段分组:按照gender分组
Map<Boolean,List<User>> groupList = list.stream().collect(Collectors.groupingBy(User::getGender));
//遍历结果集
for(Map.Entry<Boolean,List<User>> entryUser :groupList.entrySet()){
Boolean key = entryUser.getKey();
List<User> entryUserList = entryUser.getValue();
System.out.println("key:"+key +",value:"+entryUserList.toString());
}
System.out.println("#############################################################");
//知道key值,可如下输出分组的结果
groupList.get(true).forEach(e->{
System.out.println("男:"+e.toString());
});
System.out.println("#############################################################");
groupList.get(false).forEach(e->{
System.out.println("女:"+e.toString());
});
System.out.println("#############################################################");
//2.2多字段分组(多个字段,用下划线拼接):按照年龄、gender分组
Map<Object,List<User>> groupList2 = list.stream().collect(Collectors.groupingBy(o ->{
StringBuffer bf = new StringBuffer();
bf.append(o.getAge()).append("_");
bf.append(o.getGender());
return bf.toString();
}));
System.out.println(JSON.toJSONString(groupList2, SerializerFeature.PrettyFormat));
}
}
5.List集合最值:使用jdk8的Stream来获取list集合的最小值、最大值、总和、平均数
public class ListMaxMin {
public static void main(String[] args) {
//构建测试数据
List<User> list = new ArrayList<User>();
list.add(new User("张丹",11,new BigDecimal(11)));
list.add(new User("刘大",13,new BigDecimal(13)));
list.add(new User("飒飒",16,new BigDecimal(16)));
list.add(new User("斯蒂芬",11,new BigDecimal(11)));
//获取用户年龄的最大、最小、总和、平均值
int max = list.stream().mapToInt(u->u.getAge()).max().getAsInt();
int min = list.stream().mapToInt(u->u.getAge()).min().getAsInt();
//求和
//求和:分基本类型和大数据类型,基本类型先mapToInt方法,然后调用sun方法;大数类型使用reduce调用BigDecimal::add方法
//基本类型求和
int sum = list.stream().mapToInt(u->u.getAge()).sum();
//BigDecimal求和
BigDecimal totalQuantity = list.stream().map(u->u.getFamilyMemberQuantity()).reduce(BigDecimal.ZERO,BigDecimal::add);
double avg = list.stream().mapToInt(u->u.getAge()).average().getAsDouble();
System.out.println("年龄最大值:"+max+"\n年龄最小值:"+min);
System.out.println("年龄总和:"+sum+"\n年龄平均值:"+avg);
System.out.println("成员数量总和:"+totalQuantity);
}
}
6.List集合合并:合并两个list,并将userId相同的其它属性合并
public class ListMerge {
public static void main(String[] args) {
mergeList();
}
/**
* @Description: 合并两个list<map>,并将userId相同的其它属性合并
* @Title: mergeList
* @param: @return
* @return: List<Map<String,Object>>
* @throws
*/
public static List<Map<String,Object>> mergeList(){
//构建list1集合数据
List<Map<String,Object>> list1 = new ArrayList<>();
Map<String,Object> data=new HashMap<>();
data.put("userId","100001");
data.put("userName","唐僧");
list1.add(data);
data=new HashMap<>();
data.put("userId","100002");
data.put("userName","八戒");
list1.add(data);
data=new HashMap<>();
data.put("userId","100003");
data.put("userName","悟空");
list1.add(data);
data=new HashMap<>();
data.put("userId","100004");
data.put("userName","沙僧");
list1.add(data);
//构建list2集合数据
List<Map<String,Object>> list2 = new ArrayList<>();
data=new HashMap<>();
data.put("userId","100001");
data.put("gender","男");
data.put("age",20);
list2.add(data);
data=new HashMap<>();
data.put("userId","100002");
data.put("gender","雄");
data.put("age",1000);
list2.add(data);
data=new HashMap<>();
data.put("userId","100003");
data.put("gender","雄");
data.put("age",600);
list2.add(data);
data=new HashMap<>();
data.put("userId","100004");
data.put("gender","男");
data.put("age",800);
list2.add(data);
//steam():把一个源数据,可以是集合,数组,I/O channel, 产生器generator 等,转化成流。
//forEach():迭代流中的每个数据
//map():用于映射每个元素到对应的结果
//filter():用于通过设置的条件过滤出元素
//Collectors(): 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串:
//属性合并:根据userId把list2合并到list1的结果集中
List<Map<String, Object>> list = list1.stream().map(m -> {
list2.stream().filter(m2-> Objects.equals(m.get("userId"),m2.get("userId"))).forEach(m2-> {
m.put("gender",m2.get("gender"));
m.put("age",m2.get("age"));
});
return m;
}).collect(Collectors.toList());
//遍历输出合并后的结果集
for(Map<String, Object> map:list){
System.out.println(map.toString());
}
return list;
}
}
7.List集合合并:合并两个list,并将ticketId相同的其它属性合并
public class ListMerge1 {
public static void main(String[] args) {
mergeList();
}
/**
* @Description: 合并两个list<Ticket>,并将ticketId相同的其它属性合并
* @Title: mergeList
* @param: @return
* @return: List<Ticket>
* @throws
*/
public static List<Ticket> mergeList(){
List<Ticket> list1 = new ArrayList<>();
Ticket data=new Ticket();
data.setTicketId("100001");
data.setTicketName("唐僧");
list1.add(data);
data=new Ticket();
data.setTicketId("100002");
data.setTicketName("八戒");
list1.add(data);
data=new Ticket();
data.setTicketId("100003");
data.setTicketName("悟空");
list1.add(data);
data=new Ticket();
data.setTicketId("100004");
data.setTicketName("沙僧");
list1.add(data);
List<Ticket> list2 = new ArrayList<>();
data=new Ticket();
data.setTicketId("100001");
data.setSaleNum("20");
data.setBatchAvailableNum("10");
list2.add(data);
data=new Ticket();
data.setTicketId("100001");
data.setSaleNum("20");
data.setBatchAvailableNum("10");
list2.add(data);
data=new Ticket();
data.setTicketId("100002");
data.setSaleNum("1000");
data.setBatchAvailableNum("600");
list2.add(data);
data=new Ticket();
data.setTicketId("100003");
data.setSaleNum("600");
data.setBatchAvailableNum("100");
list2.add(data);
data=new Ticket();
data.setTicketId("100004");
data.setSaleNum("800");
data.setBatchAvailableNum("300");
list2.add(data);
//使用stream流把list1和list2根据属性ticketId合并一个list集合
List<Ticket> list = list1.stream().map(m -> {
list2.stream().filter(m2-> Objects.equals(m.getTicketId(),m2.getTicketId())).forEach(m2-> {
m.setSaleNum(m2.getSaleNum());
m.setBatchAvailableNum(m2.getBatchAvailableNum());
});
return m;
}).collect(Collectors.toList());
for(Ticket ticket:list){
System.out.println(ticket.getTicketId()+","+ticket.getTicketName()+","+ticket.getSaleNum()+","+ticket.getBatchAvailableNum());
}
return list;
}
}
8.List集合合并:合并两个list.list1合并到list2(list1的个数 < list2的个数)
public class ListMerge2 {
public static void main(String[] args) {
mergeList();
}
/**
* @Description: 合并两个list<map>,并将userId相同的其它属性合并
* @Title: mergeList
* @param: @return
* @return: List<Map<String,Object>>
* @throws
*/
public static List<Ticket> mergeList(){
List<Ticket> list1 = new ArrayList<>();
Ticket data=new Ticket();
data.setTicketId("100001");
data.setTicketName("唐僧");
list1.add(data);
data=new Ticket();
data.setTicketId("100002");
data.setTicketName("八戒");
list1.add(data);
List<Ticket> list2 = new ArrayList<>();
data=new Ticket();
data.setTicketId("100001");
data.setBatchId("1");
list2.add(data);
data=new Ticket();
data.setTicketId("100001");
data.setBatchId("2");
list2.add(data);
data=new Ticket();
data.setTicketId("100002");
data.setBatchId("1");
list2.add(data);
data=new Ticket();
data.setTicketId("100002");
data.setBatchId("2");
list2.add(data);
data=new Ticket();
data.setTicketId("100002");
data.setBatchId("3");
list2.add(data);
//使用stream流把list1合并到list2集合中,根据ticketId属性
List<Ticket> list = list2.stream().map(m -> {
list1.stream().filter(m2-> Objects.equals(m.getTicketId(),m2.getTicketId())).forEach(m2-> {
m.setTicketId(m2.getTicketId());
m.setTicketName(m2.getTicketName());
});
return m;
}).collect(Collectors.toList());
for(Ticket ticket:list){
System.out.println(ticket.getTicketId()+","+ticket.getTicketName()+","+ticket.getBatchId());
}
return list;
}
}
9.List集合合并:合并两个list.list1合并到list2(list1的个数 > list2的个数)
public class ListMerge3 {
public static void main(String[] args) {
mergeList();
}
/**
* @Description: 合并两个list<map>,并将userId相同的其它属性合并
* @Title: mergeList
* @param: @return
* @return: List<Map<String,Object>>
* @throws
*/
public static List<Ticket> mergeList(){
List<Ticket> list1 = new ArrayList<>();
Ticket data=new Ticket();
data.setTicketId("100001");
data.setTicketName("唐僧");
list1.add(data);
data=new Ticket();
data.setTicketId("100002");
data.setTicketName("八戒");
list1.add(data);
List<Ticket> list2 = new ArrayList<>();
data=new Ticket();
data.setTicketId("100001");
data.setBatchId("1");
list2.add(data);
data=new Ticket();
data.setTicketId("100001");
data.setBatchId("2");
list2.add(data);
// data=new Ticket();
// data.setTicketId("100002");
// data.setBatchId("1");
// list2.add(data);
//
// data=new Ticket();
// data.setTicketId("100002");
// data.setBatchId("2");
// list2.add(data);
//
// data=new Ticket();
// data.setTicketId("100002");
// data.setBatchId("3");
// list2.add(data);
//使用stream流把list1合并到list2集合中,根据ticketId属性
List<Ticket> list = list2.stream().map(m -> {
list1.stream().filter(m2-> Objects.equals(m.getTicketId(),m2.getTicketId())).forEach(m2-> {
m.setTicketId(m2.getTicketId());
m.setTicketName(m2.getTicketName());
});
return m;
}).collect(Collectors.toList());
for(Ticket ticket:list){
System.out.println(ticket.getTicketId()+","+ticket.getTicketName()+","+ticket.getBatchId());
}
return list;
}
}
10.一个list 集合合并去重求和
public class ListMerge4 {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Student s1 = new Student();
s1.setId("s1");
s1.setNums(1);
s1.setSums(1);
list.add(s1);
s1 = new Student();
s1.setId("s1");
s1.setNums(2);
s1.setSums(3);
list.add(s1);
s1 = new Student();
s1.setId("s2");
s1.setNums(3);
s1.setSums(5);
list.add(s1);
//合并去重求和
List<Student> result = merge(list);
result.stream().forEach(e->{
System.out.println("id:"+e.getId()+",nums:"+e.getNums()+",sums:"+e.getSums());
});
}
/**
* 将id进行合并nums, sums 相加道回合并后的集合使用Java8的流进行处理
* @return
*/
public static List<Student> merge(List<Student> list){
List<Student> result = list.stream()
.collect(Collectors.toMap(Student::getId, a->a,(o1,o2)->{
o1.setNums(o1.getNums()+o2.getNums());
o1.setSums(o1.getSums()+o2.getSums());
return o1;
})).values().stream().collect(Collectors.toList());
return result;
}
}
11.List集合排序:单字段排序1
public class ListSort {
public static void main(String[] args) {
List<Ticket> list = new ArrayList<Ticket>();
Ticket data = new Ticket();
data.setGroupId("8a8480487c96d58f017c9b7bab7d0020");
data.setMallid("8a8481f57cca9442017ce026ddd40049");
data.setTicketId("1b82899c065d4474b85cfb809a99396a");
data.setTicketName("金卡");
data.setBatchId("7ed298bd08104cfe9ece16621c5e51ce");
data.setConvertible("0");
data.setGradeLimit("金卡");
data.setBatchAvailableNum("100");
data.setSaleNum("10");
list.add(data);
data = new Ticket();
data.setGroupId("8a8480487c96d58f017c9b7bab7d0020");
data.setMallid("8a8481f57cca9442017ce026ddd40049");
data.setTicketId("5ecd6634026c45edaca8b4ebfdf3964c");
data.setTicketName("电子券001");
data.setBatchId("2d29984f938b446b9174a24233b64b39");
data.setConvertible("1");
data.setGradeLimit("都可");
data.setBatchAvailableNum("100");
data.setSaleNum("30");
list.add(data);
data = new Ticket();
data.setGroupId("8a8480487c96d58f017c9b7bab7d0020");
data.setMallid("8a8481f57cca9442017ce026ddd40049");
data.setTicketId("5ecd6634026c45edaca8b4ebfdf3964c");
data.setTicketName("电子券001");
data.setBatchId("2d29984f938b446b9174a24233b64b39");
data.setConvertible("0");
data.setGradeLimit("都可");
data.setBatchAvailableNum("100");
data.setSaleNum("3");
list.add(data);
data = new Ticket();
data.setGroupId("8a8480487c96d58f017c9b7bab7d0020");
data.setMallid("8a8481f57cca9442017ce026ddd40049");
data.setTicketId("5ecd6634026c45edaca8b4ebfdf3964c");
data.setTicketName("电子券001");
data.setBatchId("2d29984f938b446b9174a24233b64b39");
data.setConvertible("0");
data.setGradeLimit("都可");
data.setBatchAvailableNum("100");
data.setSaleNum("6");
list.add(data);
data = new Ticket();
data.setGroupId("8a8480487c96d58f017c9b7bab7d0020");
data.setMallid("8a8481f57cca9442017ce026ddd40049");
data.setTicketId("5ecd6634026c45edaca8b4ebfdf3964c");
data.setTicketName("电子券001");
data.setBatchId("2d29984f938b446b9174a24233b64b39");
data.setConvertible("0");
data.setGradeLimit("都可");
data.setBatchAvailableNum("100");
data.setSaleNum("11");
list.add(data);
data = new Ticket();
data.setGroupId("8a8480487c96d58f017c9b7bab7d0020");
data.setMallid("8a8481f57cca9442017ce026ddd40049");
data.setTicketId("96c166ce59894cf0a4f8fc14a5c94fb2");
data.setTicketName("普卡");
data.setBatchId("1c332332b0d64d729a3521ea253fe621");
data.setConvertible("1");
data.setGradeLimit("普卡");
data.setBatchAvailableNum("90");
data.setSaleNum("33");
list.add(data);
data = new Ticket();
data.setGroupId("8a8480487c96d58f017c9b7bab7d0020");
data.setMallid("8a8481f57cca9442017ce026ddd40049");
data.setTicketId("b3826676e6e14168b58a1342b049723c");
data.setTicketName("银卡");
data.setBatchId("6d32889f9ab7450fb48fedad5efcaf85");
data.setConvertible("0");
data.setGradeLimit("银卡");
data.setBatchAvailableNum("30");
data.setSaleNum("33");
list.add(data);
//根据ticketId字段进行分组
Map<String, List<Ticket>> map = list.stream().collect(Collectors.groupingBy(Ticket::getTicketId));
List<Ticket> newList = new ArrayList<Ticket>();
//取每组的第一条数据
map.forEach((s, tickets) -> {
newList.add(tickets.get(0));
});
for(Ticket ticket:newList){
System.out.println(ticket.getTicketName()+","+ticket.getConvertible()+","+ticket.getSaleNum()+","+ticket.getBatchAvailableNum());
}
System.out.println("--------------------------------------list------------------------------------");
// 根据SaleNum降序
newList.sort(Comparator.comparing(Ticket::getSaleNum).reversed());
//BatchAvailableNum降序
newList.sort(Comparator.comparing(Ticket::getBatchAvailableNum).reversed());
for(Ticket ticket:newList){
System.out.println("ticketName:"+ticket.getTicketName()+",convertible:"+ticket.getConvertible()+",saleNum:"+ticket.getSaleNum()+",batchAvailableNum:"+ticket.getBatchAvailableNum());
}
}
}
12.List集合排序:单字段排序2
public class ListSortMultiple {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Ticket> list = new ArrayList<Ticket>();
Ticket data = new Ticket();
data.setTicketName("测试券1");
data.setConvertible("0");
data.setCreateDate(sdf.parse("2022-01-05 22:56:03"));
data.setExEndTime(sdf.parse("2022-01-31 23:59:59"));
data.setExIntegral("1");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("11");
list.add(data);
data = new Ticket();
data.setTicketName("测试券2");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-05 22:54:11"));
data.setExEndTime(sdf.parse("2022-01-31 23:59:59"));
data.setExIntegral("1");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("31");
list.add(data);
data = new Ticket();
data.setTicketName("测试券3");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-05 22:52:06"));
data.setExEndTime(sdf.parse("2022-01-31 23:59:59"));
data.setExIntegral("1");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("41");
list.add(data);
data = new Ticket();
data.setTicketName("测试券4");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-07 17:03:42"));
data.setExEndTime(sdf.parse("2022-01-31 23:59:59"));
data.setExIntegral("10");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("12");
list.add(data);
data = new Ticket();
data.setTicketName("测试券5");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-05 14:10:09"));
data.setExEndTime(sdf.parse("2022-01-15 23:59:59"));
data.setExIntegral("0");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("11");
list.add(data);
data = new Ticket();
data.setTicketName("测试券6");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-05 09:48:43"));
data.setExEndTime(sdf.parse("2022-01-12 23:59:59"));
data.setExIntegral("0");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("8");
list.add(data);
data = new Ticket();
data.setTicketName("测试券7");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-05 22:58:27"));
data.setExEndTime(sdf.parse("2022-01-31 23:59:59"));
data.setExIntegral("1200");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("16");
list.add(data);
data = new Ticket();
data.setTicketName("测试券8");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-10 17:56:44"));
data.setExEndTime(sdf.parse("2022-01-31 23:59:59"));
data.setExIntegral("1000");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("21");
list.add(data);
data = new Ticket();
data.setTicketName("测试券9");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-05 21:54:37"));
data.setExEndTime(sdf.parse("2022-01-12 23:59:59"));
data.setExIntegral("9");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("2");
list.add(data);
data = new Ticket();
data.setTicketName("测试1券");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2022-01-11 11:27:11"));
data.setExEndTime(sdf.parse("2022-01-12 23:59:59"));
data.setExIntegral("1000");
data.setExMoney("0.01");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("1");
list.add(data);
data = new Ticket();
data.setTicketName("测试2券");
data.setConvertible("1");
data.setCreateDate(sdf.parse("2021-12-23 14:35:57"));
data.setExEndTime(sdf.parse("2022-01-13 23:59:59"));
data.setExIntegral("50");
data.setExMoney("0");
data.setIsSoldOut("1");
data.setIsSpike("0");
data.setSaleNum("2");
list.add(data);
for(Ticket ticket:list){
System.out.println(ticket.getTicketName()+","+ticket.getConvertible()+","+ticket.getSaleNum()+","+ticket.getBatchAvailableNum());
}
System.out.println("--------------------------------------list------------------------------------");
//jdk8 组合降序排序
//isSoldOut desc,convertible desc,isSpike desc,saleNum desc,exIntegral desc,exMoney desc,exEndTime asc,createDate desc
//Comparator.reverseOrder():降序 Comparator.naturalOrder():升序
//方式一:多个字段排序(多余两个)
//先以属性SaleNum降序,再进行属性BatchAvailableNum升序 多个字段 后面追加即可
// List<Ticket> sortList = list.stream()
// .sorted(Comparator.comparing(Ticket::getSaleNum,Comparator.reverseOrder())
// .thenComparing(e->{
// return Integer.valueOf(e.getBatchAvailableNum());
// },Comparator.naturalOrder())
// .thenComparing(e->{
// return Integer.valueOf(e.getConvertible());
// },Comparator.reverseOrder())
// )
// .collect(Collectors.toList());
//方式二:多个字段排序(多余两个)
Collections.sort(list, Comparator.comparing(Ticket::getIsSoldOut,Comparator.reverseOrder())
.thenComparing(Ticket::getConvertible,Comparator.reverseOrder())
.thenComparing(Ticket::getIsSpike,Comparator.reverseOrder())
.thenComparing(t->Integer.parseInt(t.getSaleNum()),Comparator.reverseOrder())
.thenComparing(t->Double.valueOf(t.getExIntegral()),Comparator.reverseOrder())
.thenComparing(t->Double.valueOf(t.getExMoney()),Comparator.reverseOrder())
.thenComparing(Ticket::getExEndTime,Comparator.naturalOrder())
.thenComparing(Ticket::getCreateDate,Comparator.reverseOrder())
);
//输出
Ticket.printTickets(list);
}
}
13.List集合:skip(long n) 方法用于跳过前n条数据
public class ListSpike {
public static void main(String[] args) {
skip(7);
}
public static void skip(long n){
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.stream().skip(n).forEach(integer -> System.out.println("integer = " + integer));
}
}
14.List集合遍历
public class ListTraverse {
public static void main(String[] args) {
//构建测试数据
List<User> list = new ArrayList<>();
list.add(new User("张三","000001",26,true,1.76, LocalDate.of(1996,1,18)));
list.add(new User("小莉","000002",21,false,1.61, LocalDate.of(2001,1,18)));
list.add(new User("李四","000003",22,true,1.83, LocalDate.of(2000,1,18)));
list.add(new User("程曦","000004",20,false,1.64, LocalDate.of(2002,1,18)));
//输出list列表
User.printUsers(list);
//示例1:list遍历
System.out.println("###############################方式一##############################");
// 方式一:for循环遍历
for(int i=0;i<list.size();i++){
User user = list.get(i);
System.out.println("姓名:"+list.get(i).getName());
}
System.out.println("###############################方式二##############################");
// 方式二:for
for(User user:list){
System.out.println("姓名:"+user.getName());
}
System.out.println("###############################方式三#############################");
// 方式三:iterator
Iterator<User> it = list.iterator();
while(it.hasNext()){
System.out.println("姓名:"+it.next().getName());
}
System.out.println("###############################方式四##############################");
// 方式四:foreach(jdk1.8之后)
list.forEach(u->{
System.out.println("姓名:"+u.getName());
});
}
}
总结
我是南国以南i记录点滴每天成长一点点,学习是永无止境的!转载请附原文链接!!!
文章来源:https://www.cnblogs.com/bgyb/p/18119161
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签: