List集合根据元素某个字段分组
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.assertj.core.util.Lists;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Long id;
private String name;
}
/**
* @author cancan.liu
* @version 1.0
* @date 2020/8/23 10:45 上午
* @desc list元素某个字段分组
* @since 1.0
*/
class GroupList {
public static void main(String[] args) {
List<Student> students = Lists.newArrayList(
new Student(1l, "猪八戒")
, new Student(1l, "典韦")
, new Student(2l, "刘备")
);
Map<Long, List<Student>> collect = students.stream().collect(Collectors.groupingBy(Student::getId));
System.out.println(collect);
// {1=[Student(id=1, name=猪八戒), Student(id=1, name=典韦)], 2=[Student(id=2, name=刘备)]}
}
}
list元素某个字段-该元素映射为map
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.assertj.core.util.Lists;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student3 {
private Long id;
private String name;
}
/**
* @author cancan.liu
* @version 1.0
* @date 2020/8/23 10:45 上午
* @desc list元素某个字段-该元素映射为map
* @since 1.0
*/
class GroupList3 {
public static void main(String[] args) {
List<Student3> students = Lists.newArrayList(
new Student3(1l, "猪八戒")
, new Student3(2l, "典韦")
, new Student3(3l, "刘备")
);
Map<Long, Student3> collect = students.stream().collect(Collectors.toMap(Student3::getId, Function.identity()));
System.out.println(collect);
// {1=Student3(id=1, name=猪八戒), 2=Student3(id=2, name=典韦), 3=Student3(id=3, name=刘备)}
}
}
List组成树结构
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Account {
private Long id;
private Long parentId;
private String name;
}
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AccountTree {
private Long id;
private Long parentId;
private String name;
private List<AccountTree> child;
}
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author cancan.liu
* @version 1.0
* @date 2020/8/23 12:14 上午
* @desc 工具类集合测试
* @since 1.0
*/
public class StreamListToTreeTest {
public static void list2Tree(List<Account> accounts) {
// 遍历需要组成树的集合,返回,对象的id和新对象映射
Map<Long, AccountTree> AccountTreeMap = accounts.stream().map(Account -> {
// 组成新对象
AccountTree AccountTree = new AccountTree();
AccountTree.setId(Account.getId());
AccountTree.setName(Account.getName());
AccountTree.setParentId(Account.getParentId());
return AccountTree;
})
// 把新对象的id和新对象组成map映射
.collect(Collectors.toMap(AccountTree::getId, Function.identity(), (a, b) -> a));
/***
* 组织新对象的孩子
* map转list
*/
List<AccountTree> collect = AccountTreeMap.values()
.stream()
// 填充对象的childs集合
.map(e -> {
if (AccountTreeMap.containsKey(e.getParentId())) {
List<AccountTree> child = AccountTreeMap.get(e.getParentId()).getChild();
if (!CollectionUtils.isEmpty(child)) {
AccountTreeMap.get(e.getParentId()).getChild().add(e);
} else {
AccountTreeMap.get(e.getParentId()).setChild(Lists.newArrayList(e));
}
} else {
return e;
}
return null;
}).filter(e -> e != null)
.collect(Collectors.toList());
System.out.println(JSONArray.toJSONString(collect));
}
public static void main(String[] args) {
Account account1 = new Account(1l, 0l, "张三");
Account account2 = new Account(2l, 1l, "里斯");
Account account3 = new Account(3l, 2l, "王武");
Account account4 = new Account(4l, 1l, "里斯");
Account account5 = new Account(5l, 0l, "铠");
List<Account> accounts = new ArrayList<Account>() {{
add(account1);
add(account2);
add(account3);
add(account4);
add(account5);
}};
list2Tree(accounts);
}
}
[
{
"child": [
{
"child": [
{
"id": 3,
"name": "王武",
"parentId": 2
}
],
"id": 2,
"name": "里斯",
"parentId": 1
},
{
"id": 4,
"name": "里斯",
"parentId": 1
}
],
"id": 1,
"name": "张三",
"parentId": 0
},
{
"id": 5,
"name": "铠",
"parentId": 0
}
]
多个集合取交集
import org.assertj.core.util.Lists;
import java.util.List;
import java.util.Optional;
/**
* @author cancan.liu
* @version 1.0
* @date 2020/8/23 10:03 上午
* @desc 多个集合取交集
* @since 1.0
*/
public class ListIntersection {
public static List<User> retainElementList(List<List<User>> elementLists) {
Optional<List<User>> result = elementLists.parallelStream()
.filter(elementList -> elementList != null && elementList.size() != 0)
.reduce((a, b) -> {
a.retainAll(b);
return a;
});
return result.orElse(Lists.newArrayList());
}
public static void main(String[] args) {
List<List<User>> lists = Lists.newArrayList();
List<User> list = Lists.newArrayList();
User user = new User(1l, "吕布");
User user2 = new User(2l, "吕布");
list.add(user);
list.add(user2);
List<User> list2 = Lists.newArrayList();
User user3 = new User(1l, "吕布");
list2.add(user3);
List<User> list3 = Lists.newArrayList();
User user4 = new User(1l, "吕布");
User user5 = new User(3l, "孙策");
list3.add(user4);
list3.add(user5);
lists.add(list);
lists.add(list2);
lists.add(list3);
List<User> strings = retainElementList(lists);
System.out.println(strings);
}
}
合并list元素的某个属性,返回集合
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.assertj.core.util.Lists;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private List<String> names;
}
/**
* @author cancan.liu
* @version 1.0
* @date 2020/8/23 10:34 上午
* @desc 合并list元素的某个属性,返回集合
* 把所有student中names集合累加
* @since 1.0
*/
class Cumulative {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>() {{
add(new Student(Lists.newArrayList("铠", "陈咬金")));
add(new Student(Lists.newArrayList("铠", "大小姐")));
}};
Set<String> collect = students.stream()
.filter(customer -> !CollectionUtils.isEmpty(customer.getNames()))
.map(Student::getNames).flatMap(List::stream).collect(Collectors.toSet());
System.out.println(collect);
// 结果 [铠, 大小姐, 陈咬金]
}
}
合并list元素中的某个属性
import com.volc.base.utils.listintersection.User;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.assertj.core.util.Lists;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student4 {
private Long id;
private List<String> names;
}
/**
* @author cancan.liu
* @version 1.0
* @date 2020/8/23 10:45 上午
* @desc 合并list
* @since 1.0
*/
class GroupList4 {
public static void main(String[] args) {
List<Student4> students = Lists.newArrayList(
new Student4(1l, Lists.newArrayList("猪八戒", "孙悟空"))
, new Student4(2l, Lists.newArrayList("典韦"))
, new Student4(3l, Lists.newArrayList("刘备"))
, new Student4(3l, Lists.newArrayList("刘禅"))
);
// 合并集合中元素的list
List<String> collect1 = students.stream().map(Student4::getNames).flatMap(List::stream).collect(Collectors.toList());
System.out.println(collect1);
// [猪八戒, 孙悟空, 典韦, 刘备, 刘禅]
// 根据元素的id分组,并收集这组中元素的字段
Map<Long, Set<List<String>>> collect = students.stream().collect(Collectors.groupingBy(Student4::getId
, Collectors.mapping(Student4::getNames, Collectors.toSet())
));
System.out.println(collect);
// {1=[[猪八戒, 孙悟空]], 2=[[典韦]], 3=[[刘备], [刘禅]]}
List<List<User>> lists = Lists.newArrayList();
List<User> list = Lists.newArrayList();
User user = new User(1l, "吕布");
User user2 = new User(2l, "吕布");
list.add(user);
list.add(user2);
List<User> list2 = Lists.newArrayList();
User user3 = new User(1l, "吕布");
list2.add(user3);
List<User> list3 = Lists.newArrayList();
User user4 = new User(1l, "吕布");
User user5 = new User(3l, "孙策");
list3.add(user4);
list3.add(user5);
lists.add(list);
lists.add(list2);
lists.add(list3);
// 合并多个集合
Set<User> collect2 = lists.stream().flatMap(List::stream).collect(Collectors.toSet());
System.out.println(collect2);
// [User(id=2, name=吕布), User(id=1, name=吕布), User(id=3, name=孙策)]
}
}
Enum枚举值转Map
package com.volc.base.utils.enumtomap;
import lombok.AllArgsConstructor;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@AllArgsConstructor
public enum SourceEnum {
A(1, "好"),
B(2, "坏");
private Integer num;
private String name;
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class EnumToMap {
public static void main(String[] args) {
Map<Integer, String> collect = Stream.of(SourceEnum.values()).collect(Collectors.toMap(SourceEnum::getNum, SourceEnum::getName));
System.out.println(collect);
}
}
分组取第一条数据
List<RegisterDO> dealDirtyRegisterFirstResultDOS = registerDOS.stream().filter(e -> e.getAppointmentId() != null)
// 根据预约id分组-取第一个
.collect(Collectors.groupingBy(RegisterDO::getAppointmentId, Collectors.collectingAndThen(toList(), value -> value.get(0))))
.values().stream().collect(toList());
字符串分割返回集合
List<String> collect = Stream.of(string.split(",")).collect(Collectors.toList());
list转数组
String[] buildSignature = new String[]{partnerKey, providerCorpId, suiteId, authCorpId, randomCode, timestamp
, bizData};
buildSignature = Arrays.stream(buildSignature).filter(x -> StringUtils.isNoneEmpty(x)).toArray(String[]::new);
拼接url参数
import com.google.common.base.Joiner;
callbackRequestMap.put("event", callbackRequest.getEvent());
callbackRequestMap.put("message_id", callbackRequest.getTaskId());
callbackRequestMap.put("random_code", callbackRequest.getRandomCode());
callbackRequestMap.put("signature", signature);
callbackRequestMap.put("timestamp", callbackRequest.getTimestamp());
String paramUrl = "?" + Joiner.on("&").withKeyValueSeparator("=").join(callbackRequestMap);
list集合多字段分组
/**
* list集合多字段分组
*/
public static void main(String[] args) {
List<Account> lists = Lists.newArrayList(new Account(1L, "1231"));
Map<String, List<Account>> collect = lists.stream().collect(groupingBy(account ->
account.getId() + "-" + account.getName()
));
}
Stream多线程处理集合数据
List<Account> collect2 = accounts.stream()
.map(shop ->
// 多线程处理数据
CompletableFuture.supplyAsync(() ->
// 执行方法,返回了集合
getData()
))
// join 操作等待所有异步操作的结果
.map(CompletableFuture::join)
// 每个线程返回的集合进行合并
.flatMap(Collection::stream).collect(toList());
public static List<Account> getData() {
List<Account> accounts = Lists.newArrayList();
for (int i = 0; i < 100; i++) {
accounts.add(new Account(1L, "1231"));
}
return accounts;
}