前言
請各大網友尊重本人原創知識分享,謹記本人部落格:南國以南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記錄點滴每天成長一點點,學習是永無止境的!轉載請附原文連結!!!
參考連結、參考連結