Java8两个list集合合并成一个list集合
为什么要用Lambda表达式和Stream流做集合的处理? 因为效率高、代码简洁、高端大气上档次啊!
现在有以下一个场景:需要将集合
A:{
"id": "12345","name": "zhangsan"}
B:{
"id": "12345", "age": 23}
合并成一个新的集合
C:{
"id": "12345","name": "zhangsan", "age": 23}
1、将listA集合转换为map
Map<String, Person> map = listA.stream().collect
(Collectors.toMap(Person ::getId, Person -> Person))
2、合并数据,这里将listA集合的数据合并到listB集合上
listB.forEach(n -> {
if(map.containsKey(n.getId())){
Person person = map.get(n.getId());
n.setName(person.getName());
}
});
3、如果主键重复了,还可以使用以下方式去重
Map<String, Person> person = listB.stream()
.collect(Collectors.toMap(Person::getId, Function.identity(), (key1, key2) -> key2));
其余干货!
1、一个集合根据主键msisdn去重,得到一个新的集合
List<Card> newList = list.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() ->new TreeSet<>(Comparator.comparing(Card::getMsisdn))),
ArrayList::new));
2、获取一个集合中,某个对象指定属性的集合 List<Long> msisdnList = kqCardList.stream().map(KqCard::getMsisdn).collect(Collectors.toList());
3、将一个long类型的集合转换为String类型的集合 List<String> msisdnStrList = msisdnList.stream().map(String::valueOf).collect(Collectors.toList());
4、遍历一个集合中,对每个对象的指定属性进行赋值(这里我对每个对象赋值了三个参数,最后一个是使用UUID做主键)
List<CmiDataAmount> cmiDataAmountList = cmiDataAmountList.stream().map(
cmiDataAmount ->{
cmiDataAmount.setCreateTime(createTime);
cmiDataAmount.setCurrentMonth(currentMonth);
cmiDataAmount.setId(UUID.randomUUID().toString());
}).collect(Collectors.toList());
5、将String类型的字符串(比如用“,”分割)转换为集合
List<String> msisdnsList = Arrays.asList(msisdns.split(",")).stream().
map(s -> String.format(s.trim())).collect(Collectors.toList());
6、遍历集合,获取类型为A的元素,并放入新集合
List<CmiDataAmount> list = cmiDataAmountList.stream().
filter(item -> item.getType().equals("A")).
collect(Collectors.toList());
7、取list集合中的两个元素,转换为一个map Map<Integer, String> collect = list.stream(). collect(Collectors.toMap(Student::getAge, Student::getName));
8.List<Map>转成一个Map // 不想覆盖,保留最初的值: lists.stream().flatMap(m -> m.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a)); // 覆盖key相同的值, lists.stream().flatMap(m -> m.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
9、如何将一个元素(对象、属性等)优雅的转换为一个集合 List<K> authcChannels = Stream.of(K).collect(Collectors.toList());
