Java BiPredicate Interface - Java 147

Java BiPredicate Interface – Java 147

Java BiPredicate Interface

常用於集合或 Stream 中的過濾條件,也可當作其他方法的傳入參數或是引用其他方法為實例, BiPredicate Interface 介紹 Collection 中的 removeIf 、 partitioningBy 與 Stream 中的 filter 、 allMatch 等方法,了解 BiPredicate 的不同操作和方法,本篇增加了範例,並透過單元測試來驗證產出結果。

@FunctionalInterface
public interface BiPredicate<T> {
    boolean test(T t, U u);
}

檔案目錄

./
   +- src
       +- test
       |   +- org
       |       +- ruoxue
       |           +- java_147
       |               +- functional
       |                   +- bipredicate
       |                       +- BiPredicateInterfaceTest.java   

單元測試

BiPredicate Interface Java 提供 Collection 中的 removeIf 、 partitioningBy 與 Stream 中的 filter 、 allMatch 等方法操作 BiPredicate Interface 。

Food

BiPredicate Interface Java 建立 Food 類別,覆寫 equals 、 hashCode ,定義屬性和方法,用來建立一個物件。

	@NoArgsConstructor
	@Getter
	@Setter
	@Builder
	public static class Food {
		private String name;
		private double quantity;
		private int type;

		public Food(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();
		}

		public boolean equals(Object object) {
			if (!(object instanceof Food)) {
				return false;
			}
			if (this == object) {
				return true;
			}
			Food other = (Food) object;
			return new EqualsBuilder().append(getName(), other.getName()).isEquals();
		}

		public int hashCode() {
			return new HashCodeBuilder().append(getName()).toHashCode();
		}
	}

Collection_removeIf

BiPredicate Interface Java 建立 BiPredicate , List 增加三個元素,移除符合條件的元素。

	@Test
	public void Collection_removeIf() {
		int expectedSize = 1;
		List<String> list = new ArrayList<>(Arrays.asList("Bacon", "Ham", "Pork"));
		BiPredicate<String, Integer> lengthGreaterThan = (s, i) -> s.length() > i;
		list.removeIf(e -> lengthGreaterThan.test(e, 3));
		System.out.println(list);
		assertEquals(expectedSize, list.size());

		List<Food> foodList = new ArrayList<>(
				Arrays.asList(new Food("Bacon", 1, 1), new Food("Ham", 2, 1), new Food("Pork", 3, 1)));
		BiPredicate<Food, String> startsWith = (o, s) -> o.name.startsWith(s);
		BiPredicate<Food, String> contains = (o, s) -> o.name.contains(s);
		foodList.removeIf(e -> startsWith.and(contains).test(e, "B"));
		System.out.println(foodList);
		assertEquals(2, foodList.size());
	}
[Ham]
[{"name":"Ham","quantity":2.0,"type":1}, {"name":"Pork","quantity":3.0,"type":1}]

Collectors_partitioningBy

BiPredicate Interface Java 建立 BiPredicate , List 增加三個元素,分區符合條件的元素。

	@Test
	public void Collectors_partitioningBy() {
		int expectedSize = 2;
		List<String> list = Arrays.asList("Bacon", "Ham", "Pork");
		BiPredicate<String, Integer> lengthGreaterThan = (s, i) -> s.length() > i;
		Map<Boolean, List<String>> map = list.stream()
				.collect(Collectors.partitioningBy(e -> lengthGreaterThan.test(e, 3)));
		System.out.println(map);
		assertEquals(expectedSize, map.size());

		List<Food> foodList = Arrays.asList(new Food("Bacon", 1, 1), new Food("Ham", 2, 1), new Food("Pork", 3, 1));
		BiPredicate<Food, String> startsWith = (o, s) -> o.name.startsWith(s);
		BiPredicate<Food, String> contains = (o, s) -> o.name.contains(s);
		Map<Boolean, List<Food>> foodMap = foodList.stream()
				.collect(Collectors.partitioningBy(e -> startsWith.and(contains).test(e, "B")));
		System.out.println(foodMap);
		assertEquals(expectedSize, foodMap.size());
	}
{false=[Ham], true=[Bacon, Pork]}
{false=[{"name":"Ham","quantity":2.0,"type":1}, {"name":"Pork","quantity":3.0,"type":1}], true=[{"name":"Bacon","quantity":1.0,"type":1}]}

Stream_filter

BiPredicate Interface in Java 建立 BiPredicate , List 增加三個元素,過濾符合條件的元素。

	@Test
	public void Stream_filter() {
		int expectedSize = 2;
		List<String> list = Arrays.asList("Bacon", "Ham", "Pork");
		BiPredicate<String, Integer> lengthGreaterThan = (s, i) -> s.length() > i;
		list = list.stream().filter(e -> lengthGreaterThan.test(e, 3)).collect(Collectors.toList());
		System.out.println(list);
		assertEquals(expectedSize, list.size());

		List<Food> foodList = Arrays.asList(new Food("Bacon", 1, 1), new Food("Ham", 2, 1), new Food("Pork", 3, 1));
		BiPredicate<Food, String> startsWith = (o, s) -> o.name.startsWith(s);
		BiPredicate<Food, String> contains = (o, s) -> o.name.contains(s);
		foodList = foodList.stream().filter(e -> startsWith.and(contains).test(e, "B")).collect(Collectors.toList());
		System.out.println(foodList);
		assertEquals(1, foodList.size());
	}
[Bacon, Pork]
[{"name":"Bacon","quantity":1.0,"type":1}]

Stream_allMatch

BiPredicate Interface in Java 建立 BiPredicate , List 增加三個元素,過濾符合條件的元素。

	@Test
	public void Stream_allMatch() {
		List<String> list = Arrays.asList("Bacon", "Ham", "Pork");
		BiPredicate<String, Integer> lengthGreaterThan = (s, i) -> s.length() > i;
		boolean result = list.stream().allMatch(e -> lengthGreaterThan.test(e, 2));
		System.out.println(result);
		assertTrue(result);

		List<Food> foodList = Arrays.asList(new Food("Bacon", 1, 1), new Food("Ham", 2, 1), new Food("Pork", 3, 1));
		BiPredicate<Food, String> startsWith = (o, s) -> o.name.startsWith(s);
		BiPredicate<Food, String> contains = (o, s) -> o.name.contains(s);
		result = foodList.stream().allMatch(e -> startsWith.and(contains).test(e, "B"));
		System.out.println(result);
		assertFalse(result);
	}
true
false

BiPredicateInterfaceTest.java

BiPredicate Interface in Java 新增單元測試,驗證 Java BiPredicate Interface Example 是否符合預期。

package org.ruoxue.java_147.functional.bipredicate;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
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 BiPredicateInterfaceTest {

	@NoArgsConstructor
	@Getter
	@Setter
	@Builder
	public static class Food {
		private String name;
		private double quantity;
		private int type;

		public Food(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();
		}

		public boolean equals(Object object) {
			if (!(object instanceof Food)) {
				return false;
			}
			if (this == object) {
				return true;
			}
			Food other = (Food) object;
			return new EqualsBuilder().append(getName(), other.getName()).isEquals();
		}

		public int hashCode() {
			return new HashCodeBuilder().append(getName()).toHashCode();
		}
	}

	@Test
	public void Collection_removeIf() {
		int expectedSize = 1;
		List<String> list = new ArrayList<>(Arrays.asList("Bacon", "Ham", "Pork"));
		BiPredicate<String, Integer> lengthGreaterThan = (s, i) -> s.length() > i;
		list.removeIf(e -> lengthGreaterThan.test(e, 3));
		System.out.println(list);
		assertEquals(expectedSize, list.size());

		List<Food> foodList = new ArrayList<>(
				Arrays.asList(new Food("Bacon", 1, 1), new Food("Ham", 2, 1), new Food("Pork", 3, 1)));
		BiPredicate<Food, String> startsWith = (o, s) -> o.name.startsWith(s);
		BiPredicate<Food, String> contains = (o, s) -> o.name.contains(s);
		foodList.removeIf(e -> startsWith.and(contains).test(e, "B"));
		System.out.println(foodList);
		assertEquals(2, foodList.size());
	}

	@Test
	public void Collectors_partitioningBy() {
		int expectedSize = 2;
		List<String> list = Arrays.asList("Bacon", "Ham", "Pork");
		BiPredicate<String, Integer> lengthGreaterThan = (s, i) -> s.length() > i;
		Map<Boolean, List<String>> map = list.stream()
				.collect(Collectors.partitioningBy(e -> lengthGreaterThan.test(e, 3)));
		System.out.println(map);
		assertEquals(expectedSize, map.size());

		List<Food> foodList = Arrays.asList(new Food("Bacon", 1, 1), new Food("Ham", 2, 1), new Food("Pork", 3, 1));
		BiPredicate<Food, String> startsWith = (o, s) -> o.name.startsWith(s);
		BiPredicate<Food, String> contains = (o, s) -> o.name.contains(s);
		Map<Boolean, List<Food>> foodMap = foodList.stream()
				.collect(Collectors.partitioningBy(e -> startsWith.and(contains).test(e, "B")));
		System.out.println(foodMap);
		assertEquals(expectedSize, foodMap.size());
	}

	@Test
	public void Stream_filter() {
		int expectedSize = 2;
		List<String> list = Arrays.asList("Bacon", "Ham", "Pork");
		BiPredicate<String, Integer> lengthGreaterThan = (s, i) -> s.length() > i;
		list = list.stream().filter(e -> lengthGreaterThan.test(e, 3)).collect(Collectors.toList());
		System.out.println(list);
		assertEquals(expectedSize, list.size());

		List<Food> foodList = Arrays.asList(new Food("Bacon", 1, 1), new Food("Ham", 2, 1), new Food("Pork", 3, 1));
		BiPredicate<Food, String> startsWith = (o, s) -> o.name.startsWith(s);
		BiPredicate<Food, String> contains = (o, s) -> o.name.contains(s);
		foodList = foodList.stream().filter(e -> startsWith.and(contains).test(e, "B")).collect(Collectors.toList());
		System.out.println(foodList);
		assertEquals(1, foodList.size());
	}

	@Test
	public void Stream_allMatch() {
		List<String> list = Arrays.asList("Bacon", "Ham", "Pork");
		BiPredicate<String, Integer> lengthGreaterThan = (s, i) -> s.length() > i;
		boolean result = list.stream().allMatch(e -> lengthGreaterThan.test(e, 2));
		System.out.println(result);
		assertTrue(result);

		List<Food> foodList = Arrays.asList(new Food("Bacon", 1, 1), new Food("Ham", 2, 1), new Food("Pork", 3, 1));
		BiPredicate<Food, String> startsWith = (o, s) -> o.name.startsWith(s);
		BiPredicate<Food, String> contains = (o, s) -> o.name.contains(s);
		result = foodList.stream().allMatch(e -> startsWith.and(contains).test(e, "B"));
		System.out.println(result);
		assertFalse(result);
	}
}

心得分享

Java BiPredicate Interface Example 使用 Lambda 表達式能讓程式碼更加簡潔與直接,取代傳統實作接口的方法,減少了很多程式碼,大幅提高可讀性, BiPredicate Interface in Java 提供了幾種 BiPredicate 常見方法的操作範例,熟悉這些方法的操作,能夠提高開發效率,節省維護上的成本。

發佈留言