com.github.fashionbrot.tool.ListUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mars-tool Show documentation
Show all versions of mars-tool Show documentation
mars-tool 工具包 https://github.com/fashionbrot/mars-tool
The newest version!
package com.github.fashionbrot.tool;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class ListUtil {
public static List deepCopy(List src) {
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
List dest = (List) in.readObject();
return dest;
}catch (Exception e){
log.error("deepCopy error",e);
}
return null;
}
public static void swapList(List list){
if (ObjectUtil.isNotEmpty(list)){
for (int i = 0; i < list.size()-1; i++) {
Collections.swap(list,i,i+1);
}
}
}
public static List getDuplicateElements(List list) {
return list.stream() // list 对应的 Stream
.collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map,键为元素,值为元素出现的次数
.entrySet().stream() // 所有 entry 对应的 Stream
.filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
.map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream
.collect(Collectors.toList()); // 转化为 List
}
}