top.doudou.common.tool.utils.ListUtils Maven / Gradle / Ivy
package top.doudou.common.tool.utils;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import top.doudou.common.tool.bean.ConvertBeanUtils;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author 傻男人<[email protected]>
* @Date: 2020/3/27
* @Description:
*/
public class ListUtils {
public static List copyList(Collection source, Class target) {
return CollectionUtils.isEmpty(source) ? Collections.emptyList() : (List)source.stream().map((s) -> ConvertBeanUtils.copyProperties(s, target)).collect(Collectors.toList());
}
public static List stringToList(String source,String split){
List list = Lists.newArrayList();
if(!source.contains(split)){
list.add(Long.valueOf(source));
return list;
}
if(StringUtils.isBlank(split)){
split = ",";
}
Arrays.asList(source.split(split)).stream().mapToLong(t-> Long.valueOf(t).longValue()).forEach(str->list.add(str));
return list;
}
public static List stringToList(String source){
return stringToList(source,",");
}
public static String listToString(List list){
if(CollectionUtils.isEmpty(list)){
return null;
}
return StringUtils.join(list.toArray(),",");
}
public static List stringToStrList(String source,String split){
List list = Lists.newArrayList();
if(!source.contains(split)){
list.add(source);
return list;
}
if(StringUtils.isBlank(split)){
split = ",";
}
Arrays.asList(source.split(split)).stream().forEach(str->list.add(str));
return list;
}
public static List stringToStrList(String source){
return stringToStrList(source,",");
}
public static E fetchOne(Collection targets) {
if (targets != null && !targets.isEmpty()) {
Iterator var1 = targets.iterator();
if (var1.hasNext()) {
E e = (E) var1.next();
return e;
} else {
return null;
}
} else {
return null;
}
}
/**
* 拆分list
*
* @param type of param
* @param source data of list
* @param from from index(included)
* @param to to index(not included)
* @return list
*/
public static List slice(List source, int from, int to) {
if (CollectionUtils.isEmpty(source)) {
return null;
}
int size = source.size();
if (to > size) {
return slice(source.stream(), from, size).collect(Collectors.toList());
} else {
return slice(source.stream(), from, to).collect(Collectors.toList());
}
}
/**
* slice
*
* @param stream Stream
* @param startIndex (included)
* @param endIndex (not included)
* @param type of param
* @return Stream
*/
public static Stream slice(Stream stream, int startIndex, int endIndex) {
return stream
.collect(Collectors.toList())
.subList(startIndex, endIndex)
.stream();
}
/**
* 将数组转换为List,如果数组为空则返回一个空list
*
* @param type of param
* @param a object array
* @return List
*/
public static List asList(T... a) {
if (null != a) {
return new ArrayList<>(Arrays.asList(a));
} else {
return new ArrayList<>(0);
}
}
}