Use composite keys in Java Map.

Overview

To use a composite key in Java Map, specify a class that holds all the fields you want to use in the composite key in the Map key. At this time, override the following method of the class used for the key.

procedure

  1. Create a class that holds the fields you want to use for the composite key.
  2. Override the methods equals and hashCode of the Object class that this class implicitly inherits.
  3. Specify the created class in the key of Map class.

Example

Consider the following class that holds sales, and manage this class with a Map that uses a composite key.

Sales class field
・ Store number
・ Sales date
・ Sales amount

Fields used for composite keys
・ Store number
・ Sales date

(1) Create a class that holds the field you want to use for the compound key.

Composite key class


package hoge;

import java.time.LocalDate;

/**Composite key*/
public class CompositeKey {

	/**Store number*/
	private final Integer shopNo;

	/**Sales date*/
	private final LocalDate salesDate;

	public CompositeKey(Integer storeNo, LocalDate salesDate) {
		this.shopNo = storeNo;
		this.salesDate = salesDate;
	}
}

(2) Override the equals method and hashCode method of that class.

  1. Open Package Explorer and select the class that has the compound key in the field.
  2. Click Menu at the top of the screen> Source (S)> "Generate hashCode () and equals () (H) ..."
  3. The dialog "Generate hashCode () and equals ()" is displayed. Press OK.
  4. The equals and hashCode methods are inserted into the composite key class.

Since the equals method and hashCode method are defined in the Object class that inherits from all classes, this operation will override the method of the Object class.

○ Reason for overriding

・ equals method By overriding
, it will be judged as the same object only when all the fields match. If you do not override it, the contents of the field will not be compared, so you cannot use it as a composite key.

・ hashCode method By overriding
, a Hash value will be generated based on the value of each field.

Composite key class with equals () and hashCode () added

Composite key class


package hoge;

import java.time.LocalDate;

/**Composite key*/
package hoge;

import java.time.LocalDate;

/**Composite key*/
public class CompositeKey {

	/**Store number*/
	private final Integer shopNo;

	/**Sales date*/
	private final LocalDate salesDate;

	public CompositeKey(Integer storeNo, LocalDate salesDate) {
		this.shopNo = storeNo;
		this.salesDate = salesDate;
	}

	/* (Non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((salesDate == null) ? 0 : salesDate.hashCode());
		result = prime * result + ((shopNo == null) ? 0 : shopNo.hashCode());
		return result;
	}

	/* (Non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CompositeKey other = (CompositeKey) obj;
		if (salesDate == null) {
			if (other.salesDate != null)
				return false;
		} else if (!salesDate.equals(other.salesDate))
			return false;
		if (shopNo == null) {
			if (other.shopNo != null)
				return false;
		} else if (!shopNo.equals(other.shopNo))
			return false;
		return true;
	}
}

③ Operation check

Store sales data in HashMap and get the value with the compound key.

○ Preparation

1. Prepare test data.
Store number Sales date Sales amount
1 2017/01/01 100
2 2017/01/02 200
3 2017/01/03 300
2. Create a class to hold sales.

Sales class


package hoge;

import java.time.LocalDate;

/**Sales record*/
public class SalesRecord {

	/**Store number*/
	private final Integer shopNo;

	/**Sales date*/
	private final LocalDate salesDate;

	/**Sales amount*/
	private final Integer sales;

	public SalesRecord(Integer storeNo, LocalDate salesDate, Integer sales) {
		this.shopNo = storeNo;
		this.salesDate = salesDate;
		this.sales = sales;
	}

	public Integer getStoreNo() {
		return shopNo;
	}

	public LocalDate getSalesDate() {
		return salesDate;
	}

	public Integer getSales() {
		return sales;
	}

	/**for test*/
	@Override
	public String toString() {
		return "SalesRecord [storeNo=" + shopNo + ", salesDate=" + salesDate + ", sales=" + sales + "]";
	}
}
3. Create a class to run the test.

Main class


package hoge;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestMain {

	public static void main(String[] args) {

		//test data
		List<SalesRecord> salesRecords = new ArrayList<>();
		salesRecords.add(new SalesRecord(1,LocalDate.of(2017,1,1),100));
		salesRecords.add(new SalesRecord(2,LocalDate.of(2017,1,2),200));
		salesRecords.add(new SalesRecord(3,LocalDate.of(2017,1,3),300));

		//Generate HashMap
		Map<CompositeKey,SalesRecord> map = new HashMap<>();

		for (SalesRecord record : salesRecords) {
			map.put(new CompositeKey(record.getStoreNo(), record.getSalesDate()), record);
		}

		//Confirm that Value can be retrieved from Key.
		System.out.println(map.get(new CompositeKey(2,LocalDate.of(2017,1,2))));
	}
}

○ Test implementation

Try to get the record from the sales amount data stored in HashMap with the following composite key.

Store number Sales date
2 2017/01/02

○ Test result

console


SalesRecord [storeNo=2, salesDate=2017-01-02, sales=200]

It was confirmed that the specified record could be retrieved.

Sample code

・ GitHub Use compound key in Java Map

The code created for testing is stored above. However, since the code posted includes the Main class, it can also be executed by copy and paste.

Confirmation environment

Recommended Posts

Use composite keys in Java Map.
Use OpenCV in Java
Use PreparedStatement in Java
[Java] How to use Map
[Java] How to use Map
How to use Java Map
Use Redis Stream in Java
Let's use Twilio in Java! (Introduction)
Get Null-safe Map values in Java
[Java] Do not use "+" in append!
JAVA (Map)
How to use classes in Java?
Do you use Stream in Java?
I tried setting Java beginners to use shortcut keys in eclipse
Multilingual Locale in Java How to use Locale
Use OpenCV_Contrib (ArUco) in Java! (Part 2-Programming)
Duplicate Map sorted by key in Java
Reverse Key from Value in Java Map
[Java] Use cryptography in the standard library
Use "Rhino" which runs JavaScript in Java
Changes in Java 11
Rock-paper-scissors in Java
[Java] Map comparison
[Java] Use Collectors.collectingAndThen
Pi in Java
FizzBuzz in Java
Use OpenCV_Contrib (ArUco) in Java! (Part 1-Build) (OpenCV-3.4.4)
[Java] Use of final in local variable declaration
[JAVA] [Spring] [MyBatis] Use IN () with SQL Builder
Why use setters/getters instead of public/private in Java
[java] sort in list
Read JSON in Java
Make Blackjack in Java
Constraint programming in Java
Put java8 in centos7
How to use Map
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Comments in Java source
How to use map
[Java] Stream API / map
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Use Interceptor in Spring
Hello World in Java
Enum reverse map Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Sort Map values in ascending key order in Java TreeMap
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
Java bidirectional map library
ASCII art in Java
Compare Lists in Java