Java TreeMap Class - Java 147

Java TreeMap Class – Java 147

Java TreeMap Class

根據其鍵的自然順序進行排序,或者根據使用的建構子在 Map 建立時提供的比較器進行排序, TreeMap Class 介紹常見的 containsKey 、 stream 、 replaceAll 、 merge 等方法,本篇增加了範例,並透過單元測試來驗證產出結果。

檔案目錄

./
   +- src
       +- test
       |   +- org
       |       +- ruoxue
       |           +- java_147
       |               +- map
       |                   +- treemap
       |                       +- TreeMapClassTest.java   

單元測試

TreeMap Class Java 提供檢查是否包含鍵值、取代、轉成陣列、合併等操作 Map 中的元素。

Fruit

TreeMap Class Java 建立 Fruit 物件,覆寫 equals 、 hashCode ,定義屬性和方法,用來建立一個物件。

	@NoArgsConstructor
	@Getter
	@Setter
	@Builder
	public static class Fruit implements Comparable<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();
		}

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

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

		@Override
		public int compareTo(Fruit o) {
			return this.name.compareTo(o.name);
		}
	}

containsKey

TreeMap Class Java 建立一個 TreeMap ,增加三個元素,檢查是否包含鍵值。

	@Test
	public void containsKey() {
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		Fruit key = new Fruit("Lemon", 3, 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		boolean containsKey = map.containsKey(key);
		System.out.println(containsKey);
		assertTrue(containsKey);
	}
true

containsValue

TreeMap Class Java 建立一個 TreeMap ,增加三個元素,檢查是否包含值。

	@Test
	public void containsValue() {
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		boolean containsValue = map.containsValue(3);
		System.out.println(containsValue);
		assertTrue(containsValue);
	}
true

stream

TreeMap Class Java 建立一個 TreeMap ,內有三個元素,使用串流,取得長度小於 6 的元素。

	@Test
	public void stream() {
		int expectedSize = 2;
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		Set<Fruit> set = map.keySet().stream().filter(e -> e.name.length() < 6).collect(Collectors.toSet());
		System.out.println(set);
		assertEquals(expectedSize, set.size());
	}
[{"name":"Lemon","quantity":3.0,"type":1}, {"name":"Grape","quantity":1.0,"type":1}]

parallelStream

TreeMap Class Java 建立一個 TreeMap ,內有三個元素,使用並行串流。

	@Test
	public void parallelStream() {
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		map.keySet().parallelStream().forEach(System.out::println);
		System.out.println("----------");
		map.keySet().parallelStream().forEachOrdered(System.out::println);
	}
{"name":"Kiwifruit","quantity":2.0,"type":1}
{"name":"Grape","quantity":1.0,"type":1}
{"name":"Lemon","quantity":3.0,"type":1}
----------
{"name":"Grape","quantity":1.0,"type":1}
{"name":"Kiwifruit","quantity":2.0,"type":1}
{"name":"Lemon","quantity":3.0,"type":1}

replace

Tree Map Class in Java 建立一個 TreeMap ,內有三個元素,取代指定 Key 元素的值。

	@Test
	public void replace() {
		Integer expected = 10;
		Map<Fruit, Integer> map = new TreeMap<>();
		Fruit key = new Fruit("Grape", 1, 1);
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		map.replace(key, 10);
		System.out.println(map);
		assertEquals(expected, map.get(key));
	}
{{"name":"Grape","quantity":1.0,"type":1}=10, {"name":"Kiwifruit","quantity":2.0,"type":1}=2, {"name":"Lemon","quantity":3.0,"type":1}=3}

replaceAll

Tree Map Class in Java 建立一個 TreeMap ,內有三個元素,取代所有元素的值。

	@Test
	public void replaceAll() {
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		map.replaceAll((k, v) -> {
			v = (int) k.getQuantity() * 10;
			return v;
		});
		System.out.println(map);
	}
{{"name":"Grape","quantity":1.0,"type":1}=10, {"name":"Kiwifruit","quantity":2.0,"type":1}=20, {"name":"Lemon","quantity":3.0,"type":1}=30}

merge

Tree Map Class in Java 建立一個 TreeMap ,內有三個元素,指定 key 值,合併 value 舊值與新值。

	@Test
	public void merge() {
		Integer expected = 11;
		Map<Fruit, Integer> map = new TreeMap<>();
		Fruit key = new Fruit("Grape", 1, 1);
		map.put(key, 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		Integer replaced = map.merge(key, 10, (oldValue, newValue) -> {
			newValue += oldValue;
			return newValue;
		});
		System.out.println(map);
		assertEquals(expected, replaced);

		Fruit newKey = new Fruit("Papaya", 4, 1);
		replaced = map.merge(newKey, 4, (oldValue, newValue) -> {
			newValue += oldValue;
			return newValue;
		});
		System.out.println(map);
		assertEquals(new Integer(4), replaced);
	}
{{"name":"Grape","quantity":1.0,"type":1}=11, {"name":"Kiwifruit","quantity":2.0,"type":1}=2, {"name":"Lemon","quantity":3.0,"type":1}=3}
{{"name":"Grape","quantity":1.0,"type":1}=11, {"name":"Kiwifruit","quantity":2.0,"type":1}=2, {"name":"Lemon","quantity":3.0,"type":1}=3, {"name":"Papaya","quantity":4.0,"type":1}=4}

TreeMapClassTest.java

Tree Map Class in Java 新增單元測試,驗證是否符合預期。

心得分享

package org.ruoxue.java_147.map.treemap;

import static org.junit.Assert.*;

import java.util.TreeMap;
import java.util.Map;
import java.util.Set;
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 TreeMapClassTest {

	@NoArgsConstructor
	@Getter
	@Setter
	@Builder
	public static class Fruit implements Comparable<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();
		}

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

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

		@Override
		public int compareTo(Fruit o) {
			return this.name.compareTo(o.name);
		}
	}

	@Test
	public void containsKey() {
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		Fruit key = new Fruit("Lemon", 3, 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		boolean containsKey = map.containsKey(key);
		System.out.println(containsKey);
		assertTrue(containsKey);
	}

	@Test
	public void containsValue() {
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		boolean containsValue = map.containsValue(3);
		System.out.println(containsValue);
		assertTrue(containsValue);
	}

	@Test
	public void stream() {
		int expectedSize = 2;
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		Set<Fruit> set = map.keySet().stream().filter(e -> e.name.length() < 6).collect(Collectors.toSet());
		System.out.println(set);
		assertEquals(expectedSize, set.size());
	}

	@Test
	public void parallelStream() {
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		map.keySet().parallelStream().forEach(System.out::println);
		System.out.println("----------");
		map.keySet().parallelStream().forEachOrdered(System.out::println);
	}

	@Test
	public void replace() {
		Integer expected = 10;
		Map<Fruit, Integer> map = new TreeMap<>();
		Fruit key = new Fruit("Grape", 1, 1);
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		map.replace(key, 10);
		System.out.println(map);
		assertEquals(expected, map.get(key));
	}

	@Test
	public void replaceAll() {
		Map<Fruit, Integer> map = new TreeMap<>();
		map.put(new Fruit("Grape", 1, 1), 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		map.replaceAll((k, v) -> {
			v = (int) k.getQuantity() * 10;
			return v;
		});
		System.out.println(map);
	}

	@Test
	public void merge() {
		Integer expected = 11;
		Map<Fruit, Integer> map = new TreeMap<>();
		Fruit key = new Fruit("Grape", 1, 1);
		map.put(key, 1);
		map.put(new Fruit("Lemon", 3, 1), 3);
		map.put(new Fruit("Kiwifruit", 2, 1), 2);
		Integer replaced = map.merge(key, 10, (oldValue, newValue) -> {
			newValue += oldValue;
			return newValue;
		});
		System.out.println(map);
		assertEquals(expected, replaced);

		Fruit newKey = new Fruit("Papaya", 4, 1);
		replaced = map.merge(newKey, 4, (oldValue, newValue) -> {
			newValue += oldValue;
			return newValue;
		});
		System.out.println(map);
		assertEquals(new Integer(4), replaced);
	}
}

Java TreeMap Class Example 提供了一個有序的鍵值對集合,其中的鍵是根據它們的自然順序,或傳遞給建構子的自定義比較器進行排序, Tree Map Class in Java 提供 containsKey 、 stream 、 replaceAll 、 merge 等操作範例。

發佈留言