JAVA8 List的去重、过滤、映射(map)、分组、统计(sum、max、min、avg)、分页

目录

1.实现List对象集合的简单去重(distinct())

2.实现List集合的根据属性(name)去重

3.实现List对象集合的简单过滤(过滤为 null 的对象)

4.实现List对象集合中获取其中某一属性(weight)的List集合

5.实现List对象集合中根据对象(Apple)的某一属性(color)进行分组

6.实现List对象集合中求和、最大、最小、平均的统计(mapToDouble())

7.实现List对象集合的分页(skip()+limit())


1.实现List对象集合的简单去重(distinct())

核心代码:

list = list.stream().distinct().collect(Collectors.toList());

底层原理:

通过将 List类型 转换为 LinkedSet类型后,根据equals()方法和对象的hashCode()去重 的方式去重。

示例如下:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Aoo> list = new ArrayList<Aoo>();
        Aoo a = new Aoo("a.name");
        Aoo b = a;
        Aoo c = new Aoo("c.name");
        list.add(a);
        list.add(b);
        list.add(c);
        System.out.println("list before operate : " + list);
        list = list.stream().distinct().collect(Collectors.toList());
        System.out.println("list after operate : " + list);
    }
  
}
class Aoo {
    private String name;

    public Aoo(String name) {
        this.name = name;
    }
    public Aoo() {}

    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Aoo [name=" + name + "]";
    }
}

执行结果:

list before operate : [Aoo [name=a.name], Aoo [name=a.name], Aoo [name=c.name]]
list after operate : [Aoo [name=a.name], Aoo [name=c.name]]

2.实现List集合的根据属性(name)去重

核心代码:(方法一)

list = list.stream().filter(o -> o.getName() != null).collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                    () -> new TreeSet<>(Comparator.comparing(o -> o.getName()))), ArrayList<Aoo>::new));

示例如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Aoo> list = Arrays.asList(new Aoo("a.name"), new Aoo("b.name"), new Aoo("c.name"));
        System.out.println("list before operate : " + list);
        list = list.stream().filter(o -> o.getName() != null).collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                    () -> new TreeSet<>(Comparator.comparing(o -> o.getName()))), ArrayList<Aoo>::new));
        System.out.println("list after operate : " + list);
    }
}
class Aoo {
    private String name;

    public Aoo(String name) {
        this.name = name;
    }
    public Aoo() {}

    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Aoo [name=" + name + "]";
    }
}

执行结果:

list before operate : [Aoo [name=a.name], Aoo [name=a.name], Aoo [name=c.name]]
list after operate : [Aoo [name=a.name], Aoo [name=c.name]]

核心代码:(方法二)

public static void main(String[] args) {
    List<String> list = new ArrayList<>(0);
    list.add("1");
    list.add("222");
    list.add("333");
    Map<Integer, String> collect = list.stream().collect(Collectors.toMap(String::length, o -> o, (v1, v2) -> v1));
    list = new ArrayList<>(collect.values());
    System.out.println("result: " + list);
}

执行结果:

list before operate : [Aoo [name=a.name], Aoo [name=a.name], Aoo [name=c.name]]
list after operate : [Aoo [name=a.name], Aoo [name=c.name]]

3.实现List对象集合的简单过滤(过滤为 null 的对象)

核心代码:

list = list.stream().filter(aoo -> aoo != null).collect(Collectors.toList());

示例如下

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {
        List<Aoo> list = Arrays.asList(new Aoo("a.name"), new Aoo("b.name"), new Aoo("c.name"), null);
        System.out.println("list before operate : " + list);
        list = list.stream().filter(aoo -> aoo != null).collect(Collectors.toList());
        System.out.println("list after operate : " + list);
    }
}

class Aoo {
    private String name;

    public Aoo(String name) {
        this.name = name;
    }
    public Aoo() {}

    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Aoo [name=" + name + "]";
    }
}

执行结果:

list before operate : [Aoo [name=a.name], Aoo [name=b.name], Aoo [name=c.name], null]
list after operate : [Aoo [name=a.name], Aoo [name=b.name], Aoo [name=c.name]]

4.实现List对象集合中获取其中某一属性(weight)的List集合

核心代码:

List<Double> collect = apples.stream().map(Apple::getWeight).collect(Collectors.toList());

示例如下:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(new Apple("yellow", 1.5), new Apple("red", 1.3), new Apple("green", 1.7));
        List<Double> collect = apples.stream().map(Apple::getWeight).collect(Collectors.toList());
        apples.forEach(System.out::println);
        collect.forEach(System.out::println);
    }
}
class Apple {
    private String color;
    private Double weight;

    public Apple(String color, Double weight) {
        this.color = color;
        this.weight = weight;
    }

    public Apple() {}

    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public Double getWeight() {
        return weight;
    }
    public void setWeight(Double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Apple [color=" + color + ", weight=" + weight + "]";
    }
}

执行结果:

Apple [color=yellow, weight=1.5]
Apple [color=red, weight=1.3]
Apple [color=green, weight=1.7]
1.5
1.3
1.7

5.实现List对象集合中根据对象(Apple)的某一属性(color)进行分组

核心代码:

Map<String, List<Apple>> applesByColor = apples.stream().collect(Collectors.groupingBy(Apple :: getColor));

示例如下:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(new Apple("yellow", 1.5), new Apple("red", 1.3), new Apple("red", 1.7));
        Map<String, List<Apple>> applesByColor = apples.stream().collect(Collectors.groupingBy(Apple::getColor));
        System.out.println("red Apples:");
        applesByColor.get("red").forEach(System.out::println);
        System.out.println("yellow Apples:");
        applesByColor.get("yellow").forEach(System.out::println);
    }
}
class Apple {
    private String color;
    private Double weight;

    public Apple(String color, Double weight) {
        this.color = color;
        this.weight = weight;
    }

    public Apple() {}

    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public Double getWeight() {
        return weight;
    }
    public void setWeight(Double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Apple [color=" + color + ", weight=" + weight + "]";
    }
}

执行结果:

red Apples:
Apple [color=red, weight=1.3]
Apple [color=red, weight=1.7]
yellow Apples:
Apple [color=yellow, weight=1.5]

嵌套分组:

User user1 = new User("zhangsan", "beijing", 10);
User user2 = new User("zhangsan", "beijing", 20);
User user3 = new User("lisi", "shanghai", 30);
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
Map<String, Map<String, List<User>>> collect
        = list.stream().collect(
                Collectors.groupingBy(
                        User::getAddress, Collectors.groupingBy(User::getName)
                )
);
System.out.println(collect);

分组计数:

Map<String, Long> collect = list.parallelStream().collect(Collectors.groupingBy(User::getAddress,Collectors.counting()));

根据某一属性,对另一属性进行分组:

Map<String, List<Long>> collect = list.parallelStream().collect(Collectors.groupingBy(User::getAddress, Collectors.mapping(User::getWeight, Collectors.toList())));

6.实现List对象集合中求和、最大、最小、平均的统计(mapToDouble())

除了统计double类型,还有int(mapToInt)和long(mapToLong)

核心代码:

double sum = apples.stream().mapToDouble(Apple::getWeight).sum(); //和
OptionalDouble max = apples.stream().mapToDouble(Apple::getWeight).max(); //最大
OptionalDouble min = apples.stream().mapToDouble(Apple::getWeight).min(); //最小
OptionalDouble average = apples.stream().mapToDouble(Apple::getWeight).average(); //平均值

示例如下:

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

public class Test {

    public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(new Apple("yellow", 1.5), new Apple("red", 1.3), new Apple("green", 1.7));
        double sum = apples.stream().mapToDouble(Apple::getWeight).sum(); //和
        OptionalDouble max = apples.stream().mapToDouble(Apple::getWeight).max(); //最大
        OptionalDouble min = apples.stream().mapToDouble(Apple::getWeight).min(); //最小
        OptionalDouble average = apples.stream().mapToDouble(Apple::getWeight).average(); //平均值
        System.out.println("sum:" + sum); //和
        System.out.println("max:" + max); //最大
        System.out.println("min:" + min); //最小
        System.out.println("average:" + average); //平均值
    }
}
class Apple {
    private String color;
    private Double weight;

    public Apple(String color, Double weight) {
        this.color = color;
        this.weight = weight;
    }
    public Apple() {}

    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public Double getWeight() {
        return weight;
    }
    public void setWeight(Double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Apple [color=" + color + ", weight=" + weight + "]";
    }
}

执行结果:

sum:4.5
max:OptionalDouble[1.7]
min:OptionalDouble[1.3]
average:OptionalDouble[1.5]

7.实现List对象集合的分页(skip()+limit())

核心代码:

List<User> resultList = list.stream().skip(pageSize * (pageNum - 1)).limit(pageSize).collect(Collectors.toList());

示例如下:

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

public class Test {

    public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(new Apple("yellow", 1.5), new Apple("red", 1.3), new Apple("green", 1.7));
        int pageNum = 2;
        int pageSize = 1;
        List<Apple> resultList = apples.stream().skip(pageSize * (pageNum - 1)).limit(pageSize).collect(Collectors.toList());
        System.out.println("resultList:" + resultList); // 第2页,每页1条数据
    }
}
class Apple {
    private String color;
    private Double weight;

    public Apple(String color, Double weight) {
        this.color = color;
        this.weight = weight;
    }
    public Apple() {}

    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public Double getWeight() {
        return weight;
    }
    public void setWeight(Double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Apple [color=" + color + ", weight=" + weight + "]";
    }
}

执行结果:

resultList:[Apple [color=red, weight=1.3]]

  • 4
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java 8中,可以使用不同的方法来对List进行去重操作。 一种方法是使用Stream进行去重。可以使用Stream的distinct()方法来消除List中的重复元素。例如: ```java List<String> list = new ArrayList<>(); list.add("test1"); list.add("test1"); list.add("test2"); list.add("test2"); list.add("test3"); List<String> uniqueList = list.stream().distinct().collect(Collectors.toList()); ``` 这将返回一个新的List,其中包含唯一的元素。 另一种方法是使用Stream的collect()方法和Collectors.toCollection()方法。可以使用这种方法来创建一个新的TreeSet,并将List中的元素添加到该Set中,由于Set的特性,重复的元素将被自动去除。然后可以将Set转换回List。例如: ```java List<String> list = new ArrayList<>(); list.add("test1"); list.add("test1"); list.add("test2"); list.add("test2"); list.add("test3"); List<String> uniqueList = list.stream() .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(String::toString))), ArrayList::new)); ``` 这将返回一个新的List,其中包含唯一的元素,并且保持了原始的元素顺序。 以上是两种常见的Java 8中对List进行去重的方法。具体使用哪种方法取决于你的需求和偏好。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java中对List去重 Stream去重的解决方法](https://download.csdn.net/download/weixin_38667403/12761286)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [java8 List去重](https://blog.csdn.net/weixin_45828554/article/details/130539843)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Java8 List去重](https://blog.csdn.net/u010741112/article/details/122366931)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不愿放下技术的小赵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值