hashmap-java

Ví dụ về HashMap trong Java

Trong bài trước, chúng ta đã tìm hiểu về HashMap trong Java, trong bài này chúng ta sẽ làm một số ví dụ về HashMap trong Java.

Ví dụ HashMap trong Java

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapExample {

	public static void main(String[] args) {

		Map<String, String> map = new HashMap<>();

		map.put("1", "1"); // put example
		map.put("2", "2");
		map.put("3", "3");
		map.put("4", null); // null value
		map.put(null, "100"); // null key

		String value = map.get("3"); // get example
		System.out.println("Key = 3, Value = " + value);

		value = map.getOrDefault("5", "Default Value");
		System.out.println("Key = 5, Value=" + value);

		boolean keyExists = map.containsKey(null);
		boolean valueExists = map.containsValue("100");

		System.out.println("keyExists=" + keyExists + ", valueExists=" + valueExists);

		Set<Entry<String, String>> entrySet = map.entrySet();
		System.out.println(entrySet);

		System.out.println("map size=" + map.size());

		Map<String, String> map1 = new HashMap<>();
		map1.putAll(map);
		System.out.println("map1 mappings= " + map1);

		String nullKeyValue = map1.remove(null);
		System.out.println("map1 null key value = " + nullKeyValue);
		System.out.println("map1 after removing null key = " + map1);

		Set<String> keySet = map.keySet();
		System.out.println("map keys = " + keySet);

		Collection<String> values = map.values();
		System.out.println("map values = " + values);

		map.clear();
		System.out.println("map is empty=" + map.isEmpty());

	}

}Code language: JavaScript (javascript)

Output:

LUYỆN THI CHỨNG CHỈ OCA


Key = 3, Value = 3
Key = 5, Value=Default Value
keyExists=true, valueExists=true
[null=100, 1=1, 2=2, 3=3, 4=null]
map size=5
map1 mappings= {null=100, 1=1, 2=2, 3=3, 4=null}
map1 null key value = 100
map1 after removing null key = {1=1, 2=2, 3=3, 4=null}
map keys = [null, 1, 2, 3, 4]
map values = [100, 1, 2, 3, null]
map is empty=true
Code language: PHP (php)

HashMap hoạt động Java như thế nào?

HashMap trong Java sử dụng Node lớp bên trong của nó là Node để lưu trữ các ánh xạ. HashMap hoạt động trên thuật toán băm và sử dụng phương thức hashCode() và equals() trên khóa cho các phép toán get và put.

HashMap sử dụng danh sách được liên kết đơn lẻ để lưu trữ các phần tử, chúng được gọi là thùng hoặc thùng. Khi chúng ta gọi phương thức put, mã băm của khóa được sử dụng để xác định nhóm sẽ được sử dụng để lưu trữ ánh xạ.

Sau khi nhóm được xác định, Mã băm được sử dụng để kiểm tra xem đã có một khóa có cùng Mã băm hay chưa. Nếu có một khóa hiện tại có cùng Mã băm, thì phương thức equals() được sử dụng trên khóa. Nếu giá trị bằng trả về true, thì giá trị sẽ bị ghi đè, nếu không thì một ánh xạ mới sẽ được thực hiện cho nhóm danh sách được liên kết duy nhất này. Nếu không có khóa nào có cùng Mã băm thì ánh xạ sẽ được chèn vào nhóm.

Đối với hoạt động nhận HashMap, một lần nữa Mã băm khóa được sử dụng để xác định nhóm cần tìm kiếm giá trị. Sau khi nhóm được xác định, các mục nhập sẽ được duyệt để tìm ra Mục nhập bằng cách sử dụng phương thức hashCode và equals. Nếu tìm thấy kết quả phù hợp, giá trị được trả về nếu không trả về null.

Còn nhiều thứ khác liên quan như thuật toán băm để lấy nhóm cho khóa, băm lại ánh xạ, v.v. Nhưng đối với công việc của chúng tôi, chỉ cần nhớ rằng các hoạt động HashMap hoạt động trên Key và cần phải triển khai tốt phương thức hashCode và bằng để tránh hành vi không mong muốn . Hình ảnh dưới đây cho thấy lời giải thích của các hoạt động get và put.

java hashmap internal implementation, how hashmap works in java

Hệ số tải HashMap trong Java


Hệ số tải được sử dụng để tìm ra thời điểm HashMap sẽ được băm lại và kích thước nhóm sẽ được tăng lên. Giá trị mặc định của gầu hoặc dung tích là 16 và hệ số tải là 0,75. Ngưỡng để băm lại được tính bằng cách nhân dung lượng và hệ số tải. Vì vậy, giá trị ngưỡng mặc định sẽ là 12. Vì vậy, khi HashMap sẽ có nhiều hơn 12 ánh xạ, nó sẽ được băm lại và số thùng sẽ được tăng lên tiếp theo của lũy thừa 2, tức là 32. Lưu ý rằng dung lượng HashMap luôn là lũy thừa của 2

Hệ số tải mặc định là 0,75 cung cấp sự cân bằng tốt giữa độ phức tạp về không gian và thời gian. Nhưng bạn có thể đặt nó thành các giá trị khác nhau dựa trên yêu cầu của bạn. Nếu bạn muốn tiết kiệm dung lượng, thì bạn có thể tăng giá trị của nó lên 0,80 hoặc 0,90 nhưng khi đó các thao tác lấy / đặt sẽ mất nhiều thời gian hơn.

Java HashMap keySet

Phương thức keySet của HashMap trong Java trả về dạng xem Đặt các khóa trong HashMap. Chế độ xem Set này được hỗ trợ bởi HashMap và bất kỳ thay đổi nào trong HashMap đều được phản ánh trong Set và ngược lại. Dưới đây là một chương trình đơn giản trình bày các ví dụ về keySet của HashMap và cách thực hiện nếu bạn muốn keySet không được bản đồ hỗ trợ.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class HashMapKeySetExample {

	public static void main(String[] args) {

		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", "3");

		Set<String> keySet = map.keySet();
		System.out.println(keySet);

		map.put("4", "4");
		System.out.println(keySet); // keySet is backed by Map

		keySet.remove("1");
		System.out.println(map); // map is also modified

		keySet = new HashSet<>(map.keySet()); // copies the key to new Set
		map.put("5", "5");
		System.out.println(keySet); // keySet is not modified
	}

}Code language: JavaScript (javascript)

Output:

[1, 2, 3]
[1, 2, 3, 4]
{2=2, 3=3, 4=4}
[2, 3, 4]

Java HashMap values

Phương thức valuess() HashMap trong Javatrả về dạng xem Collection của các giá trị trong Map. Collections này được hỗ trợ bởi HashMap, vì vậy bất kỳ thay đổi nào trong HashMap sẽ phản ánh trong bộ sưu tập giá trị và ngược lại. Một ví dụ đơn giản dưới đây xác nhận hành vi này của bộ sưu tập giá trị HashMap.



import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class HashMapValuesExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", null);
		map.put("4", null);
		map.put(null, "100");

		Collection<String> values = map.values();
		System.out.println("map values = " + values);

		map.remove(null);
		System.out.println("map values after removing null key = " + values);

		map.put("5", "5");
		System.out.println("map values after put = " + values);

		System.out.println(map);
		values.remove("1"); // changing values collection
		System.out.println(map); // updates in map too

	}

}
Code language: JavaScript (javascript)

Output.


map values = [100, 1, 2, null, null]
map values after removing null key = [1, 2, null, null]
map values after put = [1, 2, null, null, 5]
{1=1, 2=2, 3=null, 4=null, 5=5}
{2=2, 3=null, 4=null, 5=5}
Code language: JavaScript (javascript)

Java HashMap entrySet

Phương thức entrySet() trả về dạng xem Set của các ánh xạ. EntrySet này được hỗ trợ bởi HashMap, vì vậy bất kỳ thay đổi nào trong bản đồ đều phản ánh trong tập hợp mục nhập và ngược lại. Hãy xem chương trình ví dụ dưới đây để biết ví dụ về HashMap entrySet.


import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapEntrySetExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", null);
		map.put(null, "100");

		Set<Entry<String,String>> entrySet = map.entrySet();
		Iterator<Entry<String, String>> iterator = entrySet.iterator();
		Entry<String, String> next = null;
		
		System.out.println("map before processing = "+map);
		System.out.println("entrySet before processing = "+entrySet);
		while(iterator.hasNext()){
			next = iterator.next();
			System.out.println("Processing on: "+next.getValue());
			if(next.getKey() == null) iterator.remove();
		}
		
		System.out.println("map after processing = "+map);
		System.out.println("entrySet after processing = "+entrySet);
		
		Entry<String, String> simpleEntry = new AbstractMap.SimpleEntry<String, String>("1","1");
		entrySet.remove(simpleEntry);
		System.out.println("map after removing Entry = "+map);
		System.out.println("entrySet after removing Entry = "+entrySet);
	}

}
Code language: JavaScript (javascript)

Output


map before processing = {null=100, 1=1, 2=null}
entrySet before processing = [null=100, 1=1, 2=null]
Processing on: 100
Processing on: 1
Processing on: null
map after processing = {1=1, 2=null}
entrySet after processing = [1=1, 2=null]
map after removing Entry = {2=null}
entrySet after removing Entry = [2=null]
Code language: JavaScript (javascript)

Java HashMap putIfAbsent


import java.util.HashMap;
import java.util.Map;

public class HashMapPutIfAbsentExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", null);
		map.put(null, "100");

		System.out.println("map before putIfAbsent = "+map);
		String value = map.putIfAbsent("1", "4");
		System.out.println("map after putIfAbsent = "+map);
		System.out.println("putIfAbsent returns: "+value);
		
		System.out.println("map before putIfAbsent = "+map);
		value = map.putIfAbsent("3", "3");
		System.out.println("map after putIfAbsent = "+map);
		System.out.println("putIfAbsent returns: "+value);
	}

}
Code language: JavaScript (javascript)

Output;


map before putIfAbsent = {null=100, 1=1, 2=null}
map after putIfAbsent = {null=100, 1=1, 2=null}
putIfAbsent returns: 1
map before putIfAbsent = {null=100, 1=1, 2=null}
map after putIfAbsent = {null=100, 1=1, 2=null, 3=3}
putIfAbsent returns: null
Code language: JavaScript (javascript)

Java HashMap forEach


import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

public class HashMapForEachExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", null);
		map.put(null, "100");

		BiConsumer<String, String> action = new MyBiConsumer();
		map.forEach(action);
		
		//lambda expression example
		System.out.println("\nHashMap forEach lambda example\n");
		map.forEach((k,v) -> {System.out.println("Key = "+k+", Value = "+v);});
	}

}

class MyBiConsumer implements BiConsumer<String, String> {

	@Override
	public void accept(String t, String u) {
		System.out.println("Key = " + t);
		System.out.println("Processing on value = " + u);
	}

}
Code language: JavaScript (javascript)

Output;


Key = null
Processing on value = 100
Key = 1
Processing on value = 1
Key = 2
Processing on value = null

HashMap forEach lambda example

Key = null, Value = 100
Key = 1, Value = 1
Key = 2, Value = null
Code language: PHP (php)

Java HashMap replaceAll

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public class HashMapReplaceAllExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "100");

		System.out.println("map before replaceAll = " + map);
		BiFunction<String, String, String> function = new MyBiFunction();
		map.replaceAll(function);
		System.out.println("map after replaceAll = " + map);

		// replaceAll using lambda expressions
		map.replaceAll((k, v) -> {
			if (k != null) return k + v;
			else return v;});
		System.out.println("map after replaceAll lambda expression = " + map);

	}

}

class MyBiFunction implements BiFunction<String, String, String> {

	@Override
	public String apply(String t, String u) {
		if (t != null)
			return t + u;
		else
			return u;
	}

}
Code language: JavaScript (javascript)

Output;


map before replaceAll = {null=100, 1=1, 2=2}
map after replaceAll = {null=100, 1=11, 2=22}
map after replaceAll lambda example = {null=100, 1=111, 2=222}
Code language: JavaScript (javascript)

Java HashMap computeIfAbsent


import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class HashMapComputeIfAbsent {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "10");
		map.put("2", "20");
		map.put(null, "100");

		Function<String, String> function = new MyFunction();
		map.computeIfAbsent("3", function); //key not present
		map.computeIfAbsent("2", function); //key already present
		
		//lambda way
		map.computeIfAbsent("4", v -> {return v;});
		map.computeIfAbsent("5", v -> {return null;}); //null value won't get inserted
		System.out.println(map);
	}

}

class MyFunction implements Function<String, String> {

	@Override
	public String apply(String t) {
		return t;
	}
	
}
Code language: PHP (php)

Output


{null=100, 1=10, 2=20, 3=3, 4=4}
Code language: JavaScript (javascript)

Java HashMap computeIfPresent


import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public class HashMapComputeIfPresentExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "10");
		map.put("2", "20");
		map.put(null, "100");
		map.put("10", null);

		System.out.println("map before computeIfPresent = " + map);
		BiFunction<String, String, String> function = new MyBiFunction1();
		for (String key : map.keySet()) {
			map.computeIfPresent(key, function);
		}
		
		System.out.println("map after computeIfPresent = " + map);
		map.computeIfPresent("1", (k,v) -> {return null;}); // mapping will be removed
		System.out.println("map after computeIfPresent = " + map);

	}

}

class MyBiFunction1 implements BiFunction<String, String, String> {

	@Override
	public String apply(String t, String u) {
		return t + u;
	}

}
Code language: JavaScript (javascript)

Output


map before computeIfPresent = {null=100, 1=10, 2=20, 10=null}
map after computeIfPresent = {null=null100, 1=110, 2=220, 10=null}
map after computeIfPresent = {null=null100, 2=220, 10=null}
Code language: JavaScript (javascript)

Java HashMap compute


import java.util.HashMap;
import java.util.Map;

public class HashMapComputeExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "10");
		map.put("10", null);

		System.out.println("map before compute = "+map);
		for (String key : map.keySet()) {
			map.compute(key, (k,v) -> {return k+v;});
		}
		map.compute("5", (k,v) -> {return k+v;}); //key not present, v = null
		System.out.println("map after compute = "+map);
	}

}
Code language: JavaScript (javascript)

Output


map before compute = {null=10, 1=1, 2=2, 10=null}
map after compute = {null=null10, 1=11, 2=22, 5=5null, 10=10null}
Code language: PHP (php)

Java HashMap merge


import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class HashMapMergeExample {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "1");
		map.put("2", "2");
		map.put(null, "10");
		map.put("10", null);

		for (Entry<String, String> entry : map.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			//merge throws NullPointerException if key or value is null
			if(key != null && value != null) 
			map.merge(entry.getKey(), entry.getValue(), 
					(k, v) -> {return k + v;});
		}
		System.out.println(map);
		
		map.merge("5", "5", (k, v) -> {return k + v;}); // key not present
		System.out.println(map);
		
		map.merge("1", "1", (k, v) -> {return null;}); // method return null, so remove
		System.out.println(map);

	}

}
Code language: JavaScript (javascript)

Output


{null=10, 1=11, 2=22, 10=null}
{null=10, 1=11, 2=22, 5=5, 10=null}
{null=10, 2=22, 5=5, 10=null}Code language: JavaScript (javascript)

Tổng kết

Trên đây là một số ví dụ về HashMap trong Java, chúc bạn học tốt

Nguồn video: Coding with John

Bài viết liên quan

Trả lời

Email của bạn sẽ không được hiển thị công khai.

Tài liệu + Khóa học lập trình FREE
Tài liệu + Khóa học lập trình FREE

DMCA.com Protection Status