Initialize LinkedHashMap in Java - Java 147

Initialize LinkedHashMap in Java – Java 147

Initialize LinkedHashMap in Java

初始化 LinkedHashMap 鍵和值不能直接用於基本類型,如 int 、 char 等,必須將基本型別其包裝成類別,才能存入集合,介紹常見的 put 、 putAll 、 doubleBrace 、 immutableMap 等方法,了解初始化 Map 的不同操作和方法, Initialize LinkedHashMap Java 會隨著元素增加或移除,大小自動增長或縮小,本篇增加了範例,並透過單元測試來驗證產出結果。

檔案目錄

./
   +- src
       +- test
       |   +- org
       |       +- ruoxue
       |           +- java_147
       |               +- map
       |                   +- linkedhashmap
       |                      +- InitializeLinkedHashMapTest.java   

單元測試

Java Initialize LinkedHashMap 提供初始化操作 Map 中的元素。

put

Java Initialize LinkedHashMap 建立 Fruit 物件,覆寫 equals 、 hashCode 提供給集合比較使用,建立一個 LinkedHashMap ,初始化三個元素。

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

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

	@Test
	public void put() {
		int expectedSize = 3;
		Map<String, Fruit> map = new LinkedHashMap<>();
		map.put("Grape", new Fruit("Grape", 1, 1));
		map.put("Kiwifruit", new Fruit("Kiwifruit", 2, 1));
		map.put("Lemon", new Fruit("Lemon", 3, 1));
		System.out.println(map);
		assertEquals(expectedSize, map.size());
	}
{Grape={"name":"Grape","quantity":1.0,"type":1}, Kiwifruit={"name":"Kiwifruit","quantity":2.0,"type":1}, Lemon={"name":"Lemon","quantity":3.0,"type":1}}

doubleBrace

Java Initialize LinkedHashMap 建立一個 LinkedHashMap ,初始化三個元素,代表建立並載入一個新的類別,對效能有不良影響。

	@Test
	public void doubleBrace() {
		int expectedSize = 3;
		Map<String, Fruit> map = new LinkedHashMap<String, Fruit>() {
			private static final long serialVersionUID = -1234223135233714632L;
			{
				put("Grape", new Fruit("Grape", 1, 1));
				put("Kiwifruit", new Fruit("Kiwifruit", 2, 1));
				put("Lemon", new Fruit("Lemon", 3, 1));
			}
		};
		System.out.println(map);
		assertEquals(expectedSize, map.size());
	}
{Grape={"name":"Grape","quantity":1.0,"type":1}, Kiwifruit={"name":"Kiwifruit","quantity":2.0,"type":1}, Lemon={"name":"Lemon","quantity":3.0,"type":1}}

putAll

Java Initialize LinkedHashMap 建立兩個 LinkedHashMap ,使用給定的 Map 物件,初始化三個元素。

	@Test
	public void putAll() {
		int expectedSize = 3;
		Map<String, Fruit> map = new LinkedHashMap<>();
		map.put("Grape", new Fruit("Grape", 1, 1));
		map.put("Kiwifruit", new Fruit("Kiwifruit", 2, 1));
		map.put("Lemon", new Fruit("Lemon", 3, 1));
		Map<String, Fruit> newMap = new LinkedHashMap<>();
		newMap.putAll(map);
		System.out.println(newMap);
		assertEquals(expectedSize, newMap.size());
	}
{Grape={"name":"Grape","quantity":1.0,"type":1}, Kiwifruit={"name":"Kiwifruit","quantity":2.0,"type":1}, Lemon={"name":"Lemon","quantity":3.0,"type":1}}

constructor

Java Initialize LinkedHashMap 建立一個 LinkedHashMap ,初始化三個元素。

	@Test
	public void constructor() {
		int expectedSize = 3;
		Map<String, Fruit> map = new LinkedHashMap<>();
		map.put("Grape", new Fruit("Grape", 1, 1));
		map.put("Kiwifruit", new Fruit("Kiwifruit", 2, 1));
		map.put("Lemon", new Fruit("Lemon", 3, 1));
		Map<String, Fruit> newMap = new LinkedHashMap<>(map);
		System.out.println(newMap);
		assertEquals(expectedSize, newMap.size());
	}
{Grape={"name":"Grape","quantity":1.0,"type":1}, Kiwifruit={"name":"Kiwifruit","quantity":2.0,"type":1}, Lemon={"name":"Lemon","quantity":3.0,"type":1}}

immutableMap

LinkedHashMap Initialization Java 建立一個 ImmutableMap 不可變的 Map ,初始化三個元素。

	@Test
	public void immutableMap() {
		int expectedSize = 3;
		Map<String, Fruit> map = ImmutableMap.of("Grape", new Fruit("Grape", 1, 1), "Kiwifruit",
				new Fruit("Kiwifruit", 2, 1), "Lemon", new Fruit("Lemon", 3, 1));
		System.out.println(map);
		assertEquals(expectedSize, map.size());
	}
{Grape={"name":"Grape","quantity":1.0,"type":1}, Kiwifruit={"name":"Kiwifruit","quantity":2.0,"type":1}, Lemon={"name":"Lemon","quantity":3.0,"type":1}}

removeThrowException

LinkedHashMap Initialization Java 建立一個 ImmutableMap 不可變的 Map ,初始化三個元素, 操作 remove 方法會拋出例外。

	@Test(expected = UnsupportedOperationException.class)
	public void removeThrowException() {
		int expectedSize = 3;
		Map<String, Fruit> map = ImmutableMap.of("Grape", new Fruit("Grape", 1, 1), "Kiwifruit",
				new Fruit("Kiwifruit", 2, 1), "Lemon", new Fruit("Lemon", 3, 1));
		System.out.println(map);
		assertEquals(expectedSize, map.size());
		map.remove("Grape");
	}
java.lang.UnsupportedOperationException
	at com.google.common.collect.ImmutableMap.remove(ImmutableMap.java:917)
	at org.ruoxue.java_147.map.InitializeLinkedHashMapTest.removeThrowException(InitializeLinkedHashMapTest.java:131)

InitializeLinkedHashMapTest.java

LinkedHashMap Initialization Java 新增單元測試,驗證是否符合預期。

package org.ruoxue.java_147.map.linkedhashmap;

import static org.junit.Assert.*;
import java.util.LinkedHashMap;
import java.util.Map;

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 com.google.common.collect.ImmutableMap;

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

public class InitializeLinkedHashMapTest {

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

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

	@Test
	public void put() {
		int expectedSize = 3;
		Map<String, Fruit> map = new LinkedHashMap<>();
		map.put("Grape", new Fruit("Grape", 1, 1));
		map.put("Kiwifruit", new Fruit("Kiwifruit", 2, 1));
		map.put("Lemon", new Fruit("Lemon", 3, 1));
		System.out.println(map);
		assertEquals(expectedSize, map.size());
	}

	@Test
	public void doubleBrace() {
		int expectedSize = 3;
		Map<String, Fruit> map = new LinkedHashMap<String, Fruit>() {
			private static final long serialVersionUID = -1234223135233714632L;
			{
				put("Grape", new Fruit("Grape", 1, 1));
				put("Kiwifruit", new Fruit("Kiwifruit", 2, 1));
				put("Lemon", new Fruit("Lemon", 3, 1));
			}
		};
		System.out.println(map);
		assertEquals(expectedSize, map.size());
	}

	@Test
	public void putAll() {
		int expectedSize = 3;
		Map<String, Fruit> map = new LinkedHashMap<>();
		map.put("Grape", new Fruit("Grape", 1, 1));
		map.put("Kiwifruit", new Fruit("Kiwifruit", 2, 1));
		map.put("Lemon", new Fruit("Lemon", 3, 1));
		Map<String, Fruit> newMap = new LinkedHashMap<>();
		newMap.putAll(map);
		System.out.println(newMap);
		assertEquals(expectedSize, newMap.size());
	}

	@Test
	public void constructor() {
		int expectedSize = 3;
		Map<String, Fruit> map = new LinkedHashMap<>();
		map.put("Grape", new Fruit("Grape", 1, 1));
		map.put("Kiwifruit", new Fruit("Kiwifruit", 2, 1));
		map.put("Lemon", new Fruit("Lemon", 3, 1));
		Map<String, Fruit> newMap = new LinkedHashMap<>(map);
		System.out.println(newMap);
		assertEquals(expectedSize, newMap.size());
	}

	@Test
	public void immutableMap() {
		int expectedSize = 3;
		Map<String, Fruit> map = ImmutableMap.of("Grape", new Fruit("Grape", 1, 1), "Kiwifruit",
				new Fruit("Kiwifruit", 2, 1), "Lemon", new Fruit("Lemon", 3, 1));
		System.out.println(map);
		assertEquals(expectedSize, map.size());
	}

	@Test(expected = UnsupportedOperationException.class)
	public void removeThrowException() {
		int expectedSize = 3;
		Map<String, Fruit> map = ImmutableMap.of("Grape", new Fruit("Grape", 1, 1), "Kiwifruit",
				new Fruit("Kiwifruit", 2, 1), "Lemon", new Fruit("Lemon", 3, 1));
		System.out.println(map);
		assertEquals(expectedSize, map.size());
		map.remove("Grape");
	}
}

心得分享

Java LinkedHashMap Initialize 初始化 Map ,將資料存儲在鍵、值對中,保證新增時的順序,是一個非同步的操作,插入重複鍵,會替換相應鍵的元素,LinkedHashMap Initialization Java 提供了幾種 LinkedHashMap 初始化的操作範例,使用單元測試驗證產出結果。

發佈留言