Table of Contents
ToggleCollectors Class in Java with Examples
是 JDK 中的實用類之一,包含很多實用函數,主要與 Stream API 一起使用作為終端方法,操作會因某些結果而終止,與收集器相關的函數通常在 collect() 方法中使用,提供了許多靜態方法運用, Collectors Class in Java 介紹常見的 counting 、 joining 、 mapping 、 reducing 等方法,本篇增加了範例,並透過單元測試來驗證產出結果。
檔案目錄
./
+- src
+- test
| +- org
| +- ruoxue
| +- java_147
| +- collector
| +- CollectorsWithExamplesTest.java
單元測試
Class Collectors Java 收集器類別工具,提供計數、連接字串、轉換、計算等操作集合中的元素。
Fruit
建立 Fruit 類別,覆寫 toString ,定義屬性和方法,用來建立一個物件。
@NoArgsConstructor
@Getter
@Setter
@Builder
public static class Fruit {
private String name;
private double quantity;
private int type;
public Fruit(String name, double quantity, int type) {
this.name = name;
this.quantity = quantity;
this.type = type;
}
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE);
builder.appendSuper(super.toString());
builder.append("name", name);
builder.append("quantity", quantity);
builder.append("type", type);
return builder.toString();
}
}
counting
Class Collectors Java 建立一個 List ,內有三個元素,計算符合條件元素的個數。
@Test
public void counting() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
Long result = list.stream().filter(e -> e.length() > 3).collect(Collectors.counting());
System.out.println(result);
assertEquals(2, result.longValue());
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
new Fruit("Fig", 3, 1));
Long fruitResult = fruitList.stream().filter(e -> e.getQuantity() > 0).collect(Collectors.counting());
System.out.println(fruitResult);
assertEquals(2, fruitResult.longValue());
}
2
2
collectingAndThen
Class Collectors Java 建立一個 List ,內有三個元素,特殊的收集器,允許在收集結束後立即對結果執行另一個操作。
@Test
public void collectingAndThen() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
Set<String> result = list.stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf));
System.out.println(result);
assertEquals(3, result.size());
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
new Fruit("Fig", 3, 1));
Set<Fruit> fruitResult = fruitList.stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf));
System.out.println(fruitResult);
assertEquals(3, fruitResult.size());
}
[Fig, Blueberry, Melon]
[{"name":"Blueberry","quantity":1.7976931348623157E308,"type":1}, {"name":"Fig","quantity":3.0,"type":1}, {"name":"Melon","quantity":-1.0,"type":3}]
joining
Class Collectors Java 建立一個 List ,內有三個元素,將元素連接成字串。
@Test
public void joining() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
String result = list.stream().collect(Collectors.joining(", "));
System.out.println(result);
assertEquals("Blueberry, Melon, Fig", result);
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
new Fruit("Fig", 3, 1));
String fruitResult = fruitList.stream().map(e -> e.getName())
.collect(Collectors.joining(", ", "PRE-", "-POST"));
System.out.println(fruitResult);
assertEquals("PRE-Blueberry, Melon, Fig-POST", fruitResult);
}
Blueberry, Melon, Fig
PRE-Blueberry, Melon, Fig-POST
mapping
Class Collectors Java 建立一個 List ,內有三個元素,轉換元素。
@Test
public void mapping() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
List<Integer> result = list.stream().collect(Collectors.mapping(e -> e.length(), Collectors.toList()));
System.out.println(result);
assertEquals(3, result.size());
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
new Fruit("Fig", 3, 1));
String fruitResult = fruitList.stream()
.collect(Collectors.mapping(Fruit::getName, Collectors.joining(", ", "PRE-", "-POST")));
System.out.println(fruitResult);
assertEquals("PRE-Blueberry, Melon, Fig-POST", fruitResult);
}
[9, 5, 3]
PRE-Blueberry, Melon, Fig-POST
reducing
Class Collectors Java 建立一個 List ,內有三個元素,元素屬性累加計算。
@Test
public void reducing() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
Integer result = list.stream().collect(Collectors.reducing(0, String::length, Integer::sum));
System.out.println(result);
assertEquals(17, result.intValue());
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", 1, 1), new Fruit("Melon", 2, 3),
new Fruit("Fig", 3, 1));
BigDecimal fruitResult = fruitList.stream()
.collect(Collectors.reducing(BigDecimal.ZERO, e -> new BigDecimal(e.getQuantity()), BigDecimal::add));
System.out.println(fruitResult);
assertEquals(6, fruitResult.doubleValue(), 0);
}
17
6
CollectorsWithExamplesTest.java
Class Collectors 新增單元測試,驗證是否符合預期。
package org.ruoxue.java_147.collector;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
public class CollectorsExamplesTest {
@NoArgsConstructor
@Getter
@Setter
@Builder
public static class Fruit {
private String name;
private double quantity;
private int type;
public Fruit(String name, double quantity, int type) {
this.name = name;
this.quantity = quantity;
this.type = type;
}
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE);
builder.appendSuper(super.toString());
builder.append("name", name);
builder.append("quantity", quantity);
builder.append("type", type);
return builder.toString();
}
}
@Test
public void counting() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
Long result = list.stream().filter(e -> e.length() > 3).collect(Collectors.counting());
System.out.println(result);
assertEquals(2, result.longValue());
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
new Fruit("Fig", 3, 1));
Long fruitResult = fruitList.stream().filter(e -> e.getQuantity() > 0).collect(Collectors.counting());
System.out.println(fruitResult);
assertEquals(2, fruitResult.longValue());
}
@Test
public void collectingAndThen() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
Set<String> result = list.stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf));
System.out.println(result);
assertEquals(3, result.size());
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
new Fruit("Fig", 3, 1));
Set<Fruit> fruitResult = fruitList.stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf));
System.out.println(fruitResult);
assertEquals(3, fruitResult.size());
}
@Test
public void joining() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
String result = list.stream().collect(Collectors.joining(", "));
System.out.println(result);
assertEquals("Blueberry, Melon, Fig", result);
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
new Fruit("Fig", 3, 1));
String fruitResult = fruitList.stream().map(e -> e.getName())
.collect(Collectors.joining(", ", "PRE-", "-POST"));
System.out.println(fruitResult);
assertEquals("PRE-Blueberry, Melon, Fig-POST", fruitResult);
}
@Test
public void mapping() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
List<Integer> result = list.stream().collect(Collectors.mapping(e -> e.length(), Collectors.toList()));
System.out.println(result);
assertEquals(3, result.size());
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
new Fruit("Fig", 3, 1));
String fruitResult = fruitList.stream()
.collect(Collectors.mapping(Fruit::getName, Collectors.joining(", ", "PRE-", "-POST")));
System.out.println(fruitResult);
assertEquals("PRE-Blueberry, Melon, Fig-POST", fruitResult);
}
@Test
public void reducing() {
List<String> list = Arrays.asList("Blueberry", "Melon", "Fig");
Integer result = list.stream().collect(Collectors.reducing(0, String::length, Integer::sum));
System.out.println(result);
assertEquals(17, result.intValue());
List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", 1, 1), new Fruit("Melon", 2, 3),
new Fruit("Fig", 3, 1));
BigDecimal fruitResult = fruitList.stream()
.collect(Collectors.reducing(BigDecimal.ZERO, e -> new BigDecimal(e.getQuantity()), BigDecimal::add));
System.out.println(fruitResult);
assertEquals(6, fruitResult.doubleValue(), 0);
}
}
心得分享
Collectors Class 基本上使用靜態方法對集合進行操作,提供了幾種 Collectors 常見方法的操作範例,Class Collectors 介紹常見的 counting 、 joining 、 mapping 、 reducing 等方法。