com.github.azbh111.utils.java.collection.CollectionUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils-java Show documentation
Show all versions of utils-java Show documentation
com.github.azbh111:utils-java
The newest version!
package com.github.azbh111.utils.java.collection;
import com.github.azbh111.utils.java.model.SortWrpper;
import com.github.azbh111.utils.java.iterable.IterableUtils;
import com.github.azbh111.utils.java.predicate.PredicateUtils;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
*
* @author pyz
* @date 2019/4/2 10:32 AM
*/
public class CollectionUtils {
public static void distinctByKey(Collection items, Function keyMapper) {
if (items == null || items.isEmpty()) {
return;
}
List noConflict = items.stream().filter(PredicateUtils.distinctBy(keyMapper)).collect(Collectors.toList());
items.clear();
items.addAll(noConflict);
}
/**
* 将items按给定的顺序排列
* 无匹配的在最前面
*
* @param items
* @param keys
* @param keyMapper
* @param
* @param
*/
public static void sortMissingAtFirst(Collection items, Collection keys, Function keyMapper) {
sort(items, keys, keyMapper, Integer.MIN_VALUE);
}
/**
* 将items按给定的顺序排列
* 无匹配的在最后面
*
* @param items
* @param keys
* @param keyMapper
* @param
* @param
*/
public static void sortMissingAtLast(Collection items, Collection keys, Function keyMapper) {
sort(items, keys, keyMapper, Integer.MAX_VALUE);
}
private static void sort(Collection items, Collection keys, Function keyMapper, int missingSort) {
if (items == null || items.isEmpty()) {
return;
}
if (keys == null || keys.isEmpty()) {
return;
}
Map sortMap = new HashMap<>();
int index = 0;
for (K key : keys) {
sortMap.put(key, index++);
}
List> toSort = IterableUtils.toList(items, item -> new SortWrpper(sortMap.getOrDefault(keyMapper.apply(item), missingSort), item));
Collections.sort(toSort);
items.clear();
for (SortWrpper wrapper : toSort) {
items.add(wrapper.getData());
}
}
}