public class ListUtilDx {
/**
* list 删除null
*
* @param list
* @return
*/
public static List<String> removeNull(List<String> list) {
if (null == list) {
return null;
}
Iterables.removeIf(list, Objects::isNull);
return list;
}
/**
* 去重和去除 null
*
* @param list
* @return
*/
public static List<String> distinctNull(List<String> list) {
if (null == list) {
return null;
}
return ImmutableSet.copyOf(Iterables.filter(list, Predicates.not(Predicates.isNull()))).asList();
}
/**
* 去重和去除 null
*
* @param list
* @return
*/
public static Optional<List<String>> distinctNullOptional(List<String> list) {
if (null == list) {
return Optional.empty();
}
return Optional.ofNullable(ImmutableSet.copyOf(Iterables.filter(list, Predicates.not(Predicates.isNull()))).asList());
}
/**
* 拆分 逗号 数组,并去重
*
* @param str
* @return
*/
public static Optional<List<String>> parse(String str) {
return parse(str, ",");
}
/**
* 拆分 逗号 数组,并去重
*
* @param str
* @return
*/
public static Optional<List<String>> parse(String str, String separator) {
List<String> strings = Splitter.on(separator).trimResults().omitEmptyStrings().splitToList(str);
if (null == strings || strings.size() <= 0) {
return Optional.empty();
}
return Optional.ofNullable(strings.stream().distinct().collect(Collectors.toList()));
}
/**
* list 获取 ids 数组
*
* @param list
* @param keyMapper
* @param <K>
* @param <T>
* @return
*/
public static <K, T> Optional<List<K>> parse(List<T> list, Function<? super T, ? extends K> keyMapper) {
return Optional.ofNullable(list.stream().map(keyMapper).collect(Collectors.toList()));
}
/**
* list 获取 ids 数组 并去重
*
* @param list
* @param keyMapper
* @param <K>
* @param <T>
* @return
*/
public static <K, T> Optional<List<K>> parseByDistinct(List<T> list, Function<? super T, ? extends K> keyMapper) {
return Optional.ofNullable(list.stream().map(keyMapper).distinct().collect(Collectors.toList()));
}
/**
* list 转换为 map
*
* @param list
* @param keyMapper
* @param <K>
* @param <T>
* @return
*/
public static <K, T> Map<K, T> toMap(List<T> list, Function<? super T, ? extends K> keyMapper) {
return list.stream().collect(Collectors.toMap(keyMapper, Function.identity(),
(existing, replacement) -> existing));
}
/**
* list 转换为 map
*
* @param list
* @param keyMapper
* @param keyMapper2
* @param <K>
* @param <K2>
* @param <T>
* @return
*/
public static <K, K2, T> Map<K, K2> toMap(List<T> list, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends K2> keyMapper2) {
return list.stream().collect(Collectors.toMap(keyMapper, keyMapper2, (key1, key2) -> key2));
}
/**
* 解析后,用 , 号分割,拼接(连接)成 字符串,并跳过 null 值
*
* @param list
* @return
*/
public static String toString(List<String> list) {
return toString(list, ",");
}
/**
* 解析后,用 指定 符号分割,拼接(连接)成 字符串,并跳过 null 值
*
* @param list
* @return
*/
public static String toString(List<String> list, String separator) {
return Joiner.on(separator).skipNulls().join(list);
}
}