我们经常会对list集合去重,于是我自己花了点时间将如何用 lambda表达式对list集合去重做了封装和测试,方便以后快速使用。包括对对象集合中的某个属性去重等。如果有特殊的list去重要求,可以自行对下列方法进行修改。
下列方法是本人验证过比较简便的写法,请参考:
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class ListUtil {
public static List<String> list = Arrays.asList("1","2","2","3","3","4","4","5","6","7","8");
public static List<City> cities = null;
static {
cities = new ArrayList<City>(){
{
add(new City("上海",11));
add(new City("武汉",22));
add(new City("武汉",55));
add(new City("上海",33));
add(new City("北京",33));
add(new City("深圳",43));
}
};
}
public static void main(String[] args) {
System.out.println(ListUtil.distinctElements(list));
System.out.println(ListUtil.getNoDuplicateElements(list));
System.out.println(ListUtil.getDuplicateElements(list));
System.out.println(ListUtil.getDuplicateElementsForObject(cities));
System.out.println(ListUtil.getNoDuplicateElementsForObject(cities));
System.out.println(ListUtil.getElementsAfterDuplicate(cities));
System.out.println(ListUtil.getDuplicateObject(cities));
System.out.println(ListUtil.getNoDuplicateObject(cities));
System.out.println(ListUtil.distinctObject(cities));
}
//去重后的集合 [1, 2, 3, 4, 5, 6, 7, 8]
public static <T> List<T> distinctElements(List<T> list) {
return list.stream().distinct().collect(Collectors.toList());
}
//lambda表达式 去除集合重复的值 [1, 5, 6, 7, 8]
public static <T> List<T> getNoDuplicateElements(List<T> list) {
// 获得元素出现频率的 Map,键为元素,值为元素出现的次数
Map<T, Long> map = list.stream().collect(Collectors.groupingBy(p -> p,Collectors.counting()));
System.out.println("getDuplicateElements2: "+map);
return map.entrySet().stream() // Set转换为Stream
.filter(entry -> entry.getValue() == 1) // 过滤出元素出现次数等于 1 的 entry
.map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream
.collect(Collectors.toList()); // 转化为 List
}
//lambda表达式 查找出重复的集合 [2, 3, 4]
public static <T> List<T> getDuplicateElements(List<T> list) {
return list.stream().collect(Collectors.collectingAndThen(Collectors
.groupingBy(p -> p, Collectors.counting()), map->{
map.values().removeIf(size -> size ==1); // >1 查找不重复的集合;== 1 查找重复的集合
List<T> tempList = new ArrayList<>(map.keySet());
return tempList;
}));
}
//利用set集合
public static <T> Set<T> getDuplicateElements2(List<T> list) {
Set<T> set = new HashSet<>();
Set<T> exist = new HashSet<>();
for (T s : list) {
if (set.contains(s)) {
exist.add(s);
} else {
set.add(s);
}
}
return exist;
}
/**-----------对象List做处理--------------*/
//查找对象中某个原属重复的 属性集合 [上海, 武汉]
public static List<String> getDuplicateElementsForObject(List<City> list) {
return list.stream().collect(Collectors.groupingBy(p -> p.getCity(),Collectors.counting())).entrySet().stream()
.filter(entry -> entry.getValue() > 1) // >1 查找重复的集合;== 查找不重复的集合
.map(entry -> entry.getKey())
.collect(Collectors.toList());
}
//查找对象中某个原属未重复的 属性集合 [深圳, 北京]
public static List<String> getNoDuplicateElementsForObject(List<City> list){
Map<String,List<City>> map = list.stream().collect(Collectors.groupingBy(City::getCity));
return map.entrySet().stream().filter(entry -> entry.getValue().size() == 1)
.map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream
.collect(Collectors.toList()); // 转化为 List
}
//查找对象中某个原属去重后的集合 [上海, 武汉, 北京, 深圳]
public static List<String> getElementsAfterDuplicate(List<City> list) {
return list.stream().map(o->o.getCity()).distinct().collect(Collectors.toList());
}
//对象中某个原属重复的 对象集合
// [[City(city=上海, total=11), City(city=上海, total=33)], [City(city=武汉, total=22), City(city=武汉, total=55)]]
public static List<List<City>> getDuplicateObject(List<City> list) {
return list.stream().collect(Collectors.groupingBy(City::getCity)).entrySet().stream()
.filter(entry -> entry.getValue().size() > 1) // >1 查找重复的集合;== 查找不重复的集合
.map(entry -> entry.getValue())
.collect(Collectors.toList());
}
//对象中某个原属未重复 对象集合
//[[City(city=深圳, total=43)], [City(city=北京, total=33)]]
public static List<City> getNoDuplicateObject(List<City> list) {
List<City> cities = new ArrayList<>();
list.stream().collect(Collectors.groupingBy(City::getCity)).entrySet().stream()
.filter(entry -> entry.getValue().size() ==1) //>1 查找重复的集合;== 查找不重复的集合;
.map(entry -> entry.getValue())
.forEach(p -> cities.addAll(p));
return cities;
}
//根据对象的某个原属去重后的 对象集合
//[City(city=上海, total=11), City(city=武汉, total=22), City(city=北京, total=33), City(city=深圳, total=43)]
public static List<City> distinctObject(List<City> list) {
return list.stream().filter(distinctByKey(City::getCity)).collect(Collectors.toList());
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
}
}
import java.util.*;
import java.util.stream.Collectors;
public class ListUtil_sort {
public static List<Integer> list = Arrays.asList(10,1,6,4,8,7,9,3,2,5);
public static List<City> cities = null;
public static List<City> cities2 = null;
static {
cities = new ArrayList<City>(){
{
add(new City("上海",11));
add(new City("武汉",55));
add(new City("南京",33));
add(new City("深圳",33));
}
};
cities2 = new ArrayList<City>(){
{
add(new City("上海",11,11));
add(new City("武汉",55,22));
add(new City("南京",33,55));
add(new City("深圳",33,44));
}
};
}
public static void main(String[] args) {
System.out.println(sort(list));
System.out.println(reversed(list));
System.out.println(sortForObject(cities));
System.out.println(reversedForObject(cities));
System.out.println(sortForObject2(cities2));
}
//list排序 正序
public static <T> List<T> sort(List<T> list){
return list.stream().sorted().collect(Collectors.toList());
}
//list排序 倒序
public static List<Integer> reversed(List<Integer> list){
return list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}
//根据对象某个属性排序 正序
public static List<City> sortForObject(List<City> list){
return list.stream().sorted(Comparator.comparing(City::getTotal)).collect(Collectors.toList());
}
//根据对象某个属性排序 倒序
public static List<City> reversedForObject(List<City> list){
return list.stream().sorted(Comparator.comparing(City::getTotal).reversed()).collect(Collectors.toList());
}
//根据对象两个属性排序 正序
public static List<City> sortForObject2(List<City> list){
return list.stream().sorted(Comparator.comparing(City::getTotal).thenComparing(City::getNum)).collect(Collectors.toList());
}
}
import java.util.*;
import java.util.stream.Collectors;
public class ListUtil_sum {
public static List<Integer> list = Arrays.asList(10,1,6,4,8,7,9,3,2,5);
public static List<String> strList = Arrays.asList("10","1","6","4");
public static List<City> cities = null;
public static Map<String,Integer> cityMap = null;
static {
cities = new ArrayList<City>(){
{
add(new City("上海",11));
add(new City("武汉",55));
add(new City("武汉",45));
add(new City("深圳",33));
}
};
cityMap = new HashMap<>();
cityMap.put("武汉",55);
cityMap.put("上海",11);
}
public static void main(String[] args) {
System.out.println(calculation(list));
calculation2(cities);
listToMap(cities);
mapToList(cityMap);
stringToList("上海、武汉");
joinStringValueByList(cities);
joinStringValueByList2(strList);
System.out.println(filter(cities));
}
//根据对象某个属性求各自值
///IntSummaryStatistics{count=4, sum=132, min=11, average=33.000000, max=55}
public static IntSummaryStatistics calculation(List<Integer> list){
IntSummaryStatistics stat = list.stream().collect(Collectors.summarizingInt(p -> p));
System.out.println("max:"+stat.getMax());
System.out.println("min:"+stat.getMin());
System.out.println("sum:"+stat.getSum());
System.out.println("count:"+stat.getCount());
System.out.println("average:"+stat.getAverage());
return stat;
}
//根据对象某个属性求各自值
public static void calculation2(List<City> list){
System.out.println("sum="+ list.stream().mapToInt(City::getTotal).sum());
System.out.println("max="+ list.stream().mapToInt(City::getTotal).max().getAsInt());
System.out.println("min="+ list.stream().mapToInt(City::getTotal).min().getAsInt());
System.out.println("ave="+ list.stream().mapToInt(City::getTotal).average().getAsDouble());
}
//功能描述 List转map
public static void listToMap(List<City> list){
//用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
Map<String,City> map = list.stream().collect(Collectors.toMap(City::getCity,city -> city, (k1, k2) -> k1));
map.forEach((k,v) -> System.out.println("k=" + k + ",v=" + v));
}
//对象某个属性 等于特定值的累加
public static void calculation11(List<City> list){
Map<String, IntSummaryStatistics> intSummaryStatistics = list.stream().
collect(Collectors.groupingBy(i -> i.getCity(), Collectors.summarizingInt(City::getTotal)));
System.out.println("-4-->" + intSummaryStatistics);
System.out.println("-5-->" + intSummaryStatistics.get("武汉").getSum());
}
//功能描述 map转list
public static void mapToList(Map<String,Integer> map){
List<City> list = map.entrySet().stream().map(key -> new City(key.getKey(),key.getValue())).collect(Collectors.toList());
System.out.println(list);
list.forEach(bean -> System.out.println(bean.getCity() + "," + bean.getTotal()));
}
//功能描述 字符串转list
public static void stringToList(String str){
//不需要处理
// list = Arrays.asList(str.split(","));
//需要处理
List<String> list = Arrays.asList(str.split(",")).stream().map(string -> String.valueOf(string)).collect(Collectors.toList());
list.forEach(string -> System.out.println(string));
}
//功能描述 姓名以逗号拼接
public static void joinStringValueByList(List<City> list){
System.out.println(list.stream().map(City::getCity).collect(Collectors.joining(",")));
}
//功能描述 姓名以逗号拼接
public static void joinStringValueByList2(List<String> list){
//方式一
System.out.println(String.join(",", list));
//方式二
System.out.println(list.stream().collect(Collectors.joining(",")));
}
//功能描述 过滤
public static List<City> filter(List<City> list){
return list.stream().filter(a -> a.getTotal()>44).collect(Collectors.toList());
}
}