Java Collectors partitioningBy Method - Java 147

Java Collectors partitioningBy Method – Java 147

Java Collectors partitioningBy Method

是 Collectors 類的靜態方法,將一種類型元素的收集器,允許以多種方式收集 Stream,根據特定條件的情況下,將 Stream 分區為多個分區,使用不同的下游收集器來實現更好的資料分區, PartitioningBy Java Collectors 介紹常見的 partitioningBy 等方法,本篇增加了範例,並透過單元測試來驗證產出結果。

public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) {
}

public static <T, D, A> Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,
		Collector<? super T, A, D> downstream) {
}

檔案目錄

./
   +- src
       +- test
       |   +- org
       |       +- ruoxue
       |           +- java_147
       |               +- collector
       |                   +- CollectorsPartitioningByTest.java   

單元測試

Collectors PartitioningBy 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();
		}
	}

withMaxBy

Collectors PartitioningBy Java 建立一個 List ,增加五個元素,根據指定條件進行分區,取得最大值。

	@Test
	public void withMaxBy() {
		List<String> list = Arrays.asList("Blueberry", "Melon", "Fig", "Guava", "Kiwifruit");
		Map<Boolean, Optional<String>> result = list.stream()
				.collect(Collectors.partitioningBy(e -> e.length() > 3, Collectors.maxBy(String::compareTo)));
		System.out.println(result);
		assertEquals("Fig", result.get(Boolean.FALSE).get());
		assertEquals("Melon", result.get(Boolean.TRUE).get());

		List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
				new Fruit("Fig", 3, 1), new Fruit("Guava", 4, 2), new Fruit("Kiwifruit", 5, 3));
		Map<Boolean, Optional<Fruit>> fruitResult = fruitList.stream().collect(
				Collectors.partitioningBy(e -> e.type > 1, Collectors.maxBy(Comparator.comparing(Fruit::getQuantity))));
		System.out.println(fruitResult);
		assertEquals("Blueberry", fruitResult.get(Boolean.FALSE).get().getName());
		assertEquals("Kiwifruit", fruitResult.get(Boolean.TRUE).get().getName());
	}
{false=Optional[Fig], true=Optional[Melon]}
{false=Optional[{"name":"Blueberry","quantity":1.7976931348623157E308,"type":1}], true=Optional[{"name":"Kiwifruit","quantity":5.0,"type":3}]}

withMinBy

Collectors PartitioningBy Java 建立一個 List ,增增加五個元素,根據指定條件進行分區,取得最小值。

	@Test
	public void withMinBy() {
		List<String> list = Arrays.asList("Blueberry", "Melon", "Fig", "Guava", "Kiwifruit");
		Map<Boolean, Optional<String>> result = list.stream()
				.collect(Collectors.partitioningBy(e -> e.length() > 3, Collectors.minBy(String::compareTo)));
		System.out.println(result);
		assertEquals("Fig", result.get(Boolean.FALSE).get());
		assertEquals("Blueberry", result.get(Boolean.TRUE).get());

		List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
				new Fruit("Fig", 3, 1), new Fruit("Guava", 4, 2), new Fruit("Kiwifruit", 5, 3));
		Map<Boolean, Optional<Fruit>> fruitResult = fruitList.stream().collect(
				Collectors.partitioningBy(e -> e.type > 1, Collectors.minBy(Comparator.comparing(Fruit::getQuantity))));
		System.out.println(fruitResult);
		assertEquals("Fig", fruitResult.get(Boolean.FALSE).get().getName());
		assertEquals("Melon", fruitResult.get(Boolean.TRUE).get().getName());
	}
{false=Optional[Fig], true=Optional[Blueberry]}
{false=Optional[{"name":"Fig","quantity":3.0,"type":1}], true=Optional[{"name":"Melon","quantity":-1.0,"type":3}]}

withMapping

Collectors PartitioningBy Java 建立一個 List ,增加五個元素,根據指定條件進行分區,再轉換成元素屬性,傳回 Map , Java Collectors partitioningBy 提供範例參考。

	@Test
	public void withMapping() {
		List<String> list = Arrays.asList("Blueberry", "Melon", "Fig", "Guava", "Kiwifruit");
		Map<Boolean, List<String>> result = list.stream().collect(Collectors.partitioningBy(e -> e.length() > 3,
				Collectors.mapping(e -> e.toUpperCase(), Collectors.toList())));
		System.out.println(result);
		assertEquals(1, result.get(Boolean.FALSE).size());
		assertEquals(4, result.get(Boolean.TRUE).size());

		List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
				new Fruit("Fig", 3, 1), new Fruit("Guava", 4, 2), new Fruit("Kiwifruit", 5, 3));
		Map<Boolean, List<Double>> fruitResult = fruitList.stream().collect(Collectors.partitioningBy(e -> e.type > 1,
				Collectors.mapping(Fruit::getQuantity, Collectors.toList())));
		System.out.println(fruitResult);
		assertEquals(2, fruitResult.size());
	}
{false=[FIG], true=[BLUEBERRY, MELON, GUAVA, KIWIFRUIT]}
{false=[1.7976931348623157E308, 3.0], true=[-1.0, 4.0, 5.0]}

withJoining

Collectors PartitioningBy Example 建立一個 List ,增加五個元素,根據指定條件進行分區,將元素連接成字串, Java Collectors partitioningBy 提供範例參考。

	@Test
	public void withJoining() {
		List<String> list = Arrays.asList("Blueberry", "Melon", "Fig", "Guava", "Kiwifruit");
		Map<Boolean, String> result = list.stream()
				.collect(Collectors.partitioningBy(e -> e.length() > 3, Collectors.joining(", ", "(", ")")));
		System.out.println(result);
		assertEquals(2, result.size());

		List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
				new Fruit("Fig", 3, 1), new Fruit("Guava", 4, 2), new Fruit("Kiwifruit", 5, 3));
		Map<Boolean, String> fruitResult = fruitList.stream().collect(Collectors.partitioningBy(e -> e.type > 1,
				Collectors.mapping(Fruit::getName, Collectors.joining(", ", "(", ")"))));
		System.out.println(fruitResult);
		assertEquals(2, fruitResult.size());
	}
{false=(Fig), true=(Blueberry, Melon, Guava, Kiwifruit)}
{false=(Blueberry, Fig), true=(Melon, Guava, Kiwifruit)}

CollectorsPartitioningByTest.java

Collectors PartitioningBy Example 新增單元測試,驗證 Java Collectors PartitioningBy 是否符合預期。

package org.ruoxue.java_147.collector;

import static org.junit.Assert.*;

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

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.junit.Test;

import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

public class CollectorsPartitioningByTest {

	@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 withMaxBy() {
		List<String> list = Arrays.asList("Blueberry", "Melon", "Fig", "Guava", "Kiwifruit");
		Map<Boolean, Optional<String>> result = list.stream()
				.collect(Collectors.partitioningBy(e -> e.length() > 3, Collectors.maxBy(String::compareTo)));
		System.out.println(result);
		assertEquals("Fig", result.get(Boolean.FALSE).get());
		assertEquals("Melon", result.get(Boolean.TRUE).get());

		List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
				new Fruit("Fig", 3, 1), new Fruit("Guava", 4, 2), new Fruit("Kiwifruit", 5, 3));
		Map<Boolean, Optional<Fruit>> fruitResult = fruitList.stream().collect(
				Collectors.partitioningBy(e -> e.type > 1, Collectors.maxBy(Comparator.comparing(Fruit::getQuantity))));
		System.out.println(fruitResult);
		assertEquals("Blueberry", fruitResult.get(Boolean.FALSE).get().getName());
		assertEquals("Kiwifruit", fruitResult.get(Boolean.TRUE).get().getName());
	}

	@Test
	public void withMinBy() {
		List<String> list = Arrays.asList("Blueberry", "Melon", "Fig", "Guava", "Kiwifruit");
		Map<Boolean, Optional<String>> result = list.stream()
				.collect(Collectors.partitioningBy(e -> e.length() > 3, Collectors.minBy(String::compareTo)));
		System.out.println(result);
		assertEquals("Fig", result.get(Boolean.FALSE).get());
		assertEquals("Blueberry", result.get(Boolean.TRUE).get());

		List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
				new Fruit("Fig", 3, 1), new Fruit("Guava", 4, 2), new Fruit("Kiwifruit", 5, 3));
		Map<Boolean, Optional<Fruit>> fruitResult = fruitList.stream().collect(
				Collectors.partitioningBy(e -> e.type > 1, Collectors.minBy(Comparator.comparing(Fruit::getQuantity))));
		System.out.println(fruitResult);
		assertEquals("Fig", fruitResult.get(Boolean.FALSE).get().getName());
		assertEquals("Melon", fruitResult.get(Boolean.TRUE).get().getName());
	}

	@Test
	public void withMapping() {
		List<String> list = Arrays.asList("Blueberry", "Melon", "Fig", "Guava", "Kiwifruit");
		Map<Boolean, List<String>> result = list.stream().collect(Collectors.partitioningBy(e -> e.length() > 3,
				Collectors.mapping(e -> e.toUpperCase(), Collectors.toList())));
		System.out.println(result);
		assertEquals(1, result.get(Boolean.FALSE).size());
		assertEquals(4, result.get(Boolean.TRUE).size());

		List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
				new Fruit("Fig", 3, 1), new Fruit("Guava", 4, 2), new Fruit("Kiwifruit", 5, 3));
		Map<Boolean, List<Double>> fruitResult = fruitList.stream().collect(Collectors.partitioningBy(e -> e.type > 1,
				Collectors.mapping(Fruit::getQuantity, Collectors.toList())));
		System.out.println(fruitResult);
		assertEquals(2, fruitResult.size());
	}

	@Test
	public void withJoining() {
		List<String> list = Arrays.asList("Blueberry", "Melon", "Fig", "Guava", "Kiwifruit");
		Map<Boolean, String> result = list.stream()
				.collect(Collectors.partitioningBy(e -> e.length() > 3, Collectors.joining(", ", "(", ")")));
		System.out.println(result);
		assertEquals(2, result.size());

		List<Fruit> fruitList = Arrays.asList(new Fruit("Blueberry", Double.MAX_VALUE, 1), new Fruit("Melon", -1, 3),
				new Fruit("Fig", 3, 1), new Fruit("Guava", 4, 2), new Fruit("Kiwifruit", 5, 3));
		Map<Boolean, String> fruitResult = fruitList.stream().collect(Collectors.partitioningBy(e -> e.type > 1,
				Collectors.mapping(Fruit::getName, Collectors.joining(", ", "(", ")"))));
		System.out.println(fruitResult);
		assertEquals(2, fruitResult.size());
	}
}

心得分享

Java Collectors PartitioningBy 在 Collectors 類中定義,屬於 java.util.stream ,按照不同條件下,對 Stream 進行分區,傳回 Map ,熟悉 Collectors PartitioningBy Example 這些方法的操作,例如: partitioningBy 等方法,提供更清晰、更易讀且更靈活的方式來對集合分區。

發佈留言