如何在Java 8项目中利用Stream.distinct() 方法对列表进行去重
创始人
2024-11-21 17:22:23
0次

distinct()使用hashCode()和equals()方法来获取不同的元素。因此,我们的类必须实现hashCode()和equals()方法。

如果distinct()正在处理有序流,那么对于重复元素,将保留以遭遇顺序首先出现的元素,并且以这种方式选择不同元素是稳定的。

在无序流的情况下,不同元素的选择不一定是稳定的,是可以改变的。distinct()执行有状态的中间操作。

在有序流的并行流的情况下,保持distinct()的稳定性是需要很高的代价的,因为它需要大量的缓冲开销。如果我们不需要保持遭遇顺序的一致性,那么我们应该可以使用通过BaseStream.unordered()方法实现的无序流。

1. Stream.distinct()

distinct()方法的声明如下:

Stream distinct()

它是Stream接口的方法。在此示例中,我们有一个包含重复元素的字符串数据类型列表

DistinctSimpleDemo.java

package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class DistinctSimpleDemo {
 public static void main(String[] args) {
  List list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
  long l = list.stream().distinct().count();
  System.out.println("No. of distinct elements:"+l);
  String output = list.stream().distinct().collect(Collectors.joining(","));
  System.out.println(output);
 }
} 

Output

No. of distinct elements:3

AA,BB,CC

2. Stream.distinct() with List of Objects

在此示例中,我们有一个Book对象列表。 为了对列表进行去重,该类将重写hashCode()和equals()。

Book.java

package com.concretepage;
public class Book {
 private String name;
 private int price;
 public Book(String name, int price) {
 this.name = name;
 this.price = price;
 }
 public String getName() {
 return name;
 }
 public int getPrice() {
 return price;
 }
 @Override
 public boolean equals(final Object obj) {
  if (obj == null) {
   return false;
  }
  final Book book = (Book) obj;
  if (this == book) {
   return true;
  } else {
   return (this.name.equals(book.name) && this.price == book.price);
  }
 }
 @Override
 public int hashCode() {
  int hashno = 7;
  hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
  return hashno;
 }
} 

DistinctWithUserObjects.java

package com.concretepage;
import java.util.ArrayList;
import java.util.List;
public class DistinctWithUserObjects {
 public static void main(String[] args) {
  List list = new ArrayList<>();
  {
   list.add(new Book("Core Java", 200));
   list.add(new Book("Core Java", 200));
   list.add(new Book("Learning Freemarker", 150));   
   list.add(new Book("Spring MVC", 300));
   list.add(new Book("Spring MVC", 300));
  }
  long l = list.stream().distinct().count();
  System.out.println("No. of distinct books:"+l);
  list.stream().distinct().forEach(b -> System.out.println(b.getName()+ "," + b.getPrice()));
 }
}

Output

No. of distinct books:3
Core Java,200
Learning Freemarker,150
Spring MVC,300 

3. Distinct by Property

distinct()不提供按照属性对对象列表进行去重的直接实现。它是基于hashCode()和equals()工作的。

如果我们想要按照对象的属性,对对象列表进行去重,我们可以通过其它方法来实现。

如下代码段所示:

static  Predicate distinctByKey(Function<? super T, ?> keyExtractor) {
  Map seen = new ConcurrentHashMap<>();
  return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
} 

上面的方法可以被Stream接口的 filter()接收为参数,如下所示:

list.stream().filter(distinctByKey(b -> b.getName()));

distinctByKey()方法返回一个使用ConcurrentHashMap 来维护先前所见状态的 Predicate 实例,如下是一个完整的使用对象属性来进行去重的示例。

DistinctByProperty.java

package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
public class DistinctByProperty {
 public static void main(String[] args) {
  List list = new ArrayList<>();
  {
   list.add(new Book("Core Java", 200));
   list.add(new Book("Core Java", 300));
   list.add(new Book("Learning Freemarker", 150));
   list.add(new Book("Spring MVC", 200));
   list.add(new Book("Hibernate", 300));
  }
  list.stream().filter(distinctByKey(b -> b.getName()))
    .forEach(b -> System.out.println(b.getName()+ "," + b.getPrice())); 
 }
 private static  Predicate distinctByKey(Function<? super T, ?> keyExtractor) {
  Map seen = new ConcurrentHashMap<>();
  return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
 }
} 

Output

Core Java,200
Learning Freemarker,150
Spring MVC,200
Hibernate,300 

from : https://www.concretepage.com/java/jdk-8/java-8-distinct-example

补充知识:java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLCl

在设置项目的热部署时,需要添加对 spring-boot-devtools 的依赖,因为没有给定版本号,maven默认添加的是 v 1.5.8 版本。

当时安装JDK时,看到最新的 jdk-1.9, 就顺手安装了最新版本的JDK. 但是添加依赖之后,项目启动失败,报如下异常:

Exception in thread "main" java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClassLoader
 at org.springframework.boot.devtools.restart.DefaultRestartInitializer.getUrls(DefaultRestartInitializer.java:93)
 at org.springframework.boot.devtools.restart.DefaultRestartInitializer.getInitialUrls(DefaultRestartInitializer.java:56)
 at org.springframework.boot.devtools.restart.Restarter.(Restarter.java:140)
 at org.springframework.boot.devtools.restart.Restarter.initialize(Restarter.java:546)
 at org.springframework.boot.devtools.restart.RestartApplicationListener.onApplicationStartingEvent(RestartApplicationListener.java:67)
 at org.springframework.boot.devtools.restart.RestartApplicationListener.onApplicationEvent(RestartApplicationListener.java:45)
 at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
 at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
 at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
 at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
 at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:69)
 at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:48)
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:292)
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
 at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
 at com.haiyoung.hyweb.HyWebApplication.main(HyWebApplication.java:23)

这个异常是因为老版本的 spring-boot-devtools 与最新版的 JDK之间不兼容,在网上找了找资料,关于这方面的资料没看到什么东西,上stackoverflow上找了找,也不多,就找到一个相关的,链接如下:

https://stackoverflow.com/questions/39739075/hive-shell-not-loading/41637409#41637409

大致描述如下:

In Java 9 “Application and extension class loaders are no longer instances of java.net.URLClassLoader”, see “Prepare for JDK 9”, Alan Bateman, Oct 2015: http://openjdk.java.net/projects/jigsaw/talks/prepare-for-jdk9-j1-2015.pdf. I'm not sure where exactly the problem lies, if it's in httpunit itself or the JSP compiler libraries, but you might want to run some Java 9 tests yourself.

Application and extension class loaders are no longer instances of java.net.URLClassLoader

意思是说,在 java 9中,应用程序和扩展类都不再是 java.net.URLClassLoader 的实例。

将 spring-boot-devtools 版本换成 v2.0.0.M5 重新启动项目,异常消失,项目重新启动。

不过为了避免后面太多坑,果断将JDK版本回退到 1.8,回退之后,spring-boot-devtools v1.5.8时,项目正常启动,restart 和 livereload也设置成功,正常使用。

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...