1. 程式人生 > 程式設計 >Java 8 Stream.distinct() 列表去重的操作

Java 8 Stream.distinct() 列表去重的操作

在這篇文章裡,我們將提供Java8 Stream distinct()示例。 distinct()返回由該流的不同元素組成的流。distinct()是Stream介面的方法。

distinct()使用hashCode()和equals()方法來獲取不同的元素。因此,我們的類必須實現hashCode()和equals()方法。

如果distinct()正在處理有序流,那麼對於重複元素,將保留以遭遇順序首先出現的元素,並且以這種方式選擇不同元素是穩定的。

在無序流的情況下,不同元素的選擇不一定是穩定的,是可以改變的。distinct()執行有狀態的中間操作。

在有序流的並行流的情況下,保持distinct()的穩定性是需要很高的代價的,因為它需要大量的緩衝開銷。如果我們不需要保持遭遇順序的一致性,那麼我們應該可以使用通過BaseStream.unordered()方法實現的無序流。

1. Stream.distinct()

distinct()方法的宣告如下:

Stream<T> 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<String> list = Arrays.asList("AA","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<Book> 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 <T> Predicate<T> distinctByKey(Function<? super T,?> keyExtractor) {
  Map<Object,Boolean> 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<Book> list = new ArrayList<>();
  {
   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 <T> Predicate<T> distinctByKey(Function<? super T,Boolean.TRUE) == null;
 }
} 

Output

Core Java,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.<init>(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也設定成功,正常使用。

網上也有一些其他的解決方案,不過懶得折騰,以後遇到再看。

以上這篇Java 8 Stream.distinct() 列表去重的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。