java中treemap_Java TreeMap – Java中的TreeMap

java中treemap

Java TreeMap is one of the Map implementation and it’s part of Java Collections framework.

Java TreeMap是Map实现之一,它是Java Collections框架的一部分。

Java TreeMap (Java TreeMap)

Some of the important points to remember about TreeMap in java are;

关于Java中的TreeMap,需要记住的一些重点是:

  1. Apart from implementing Map interface, Java TreeMap also implements NavigableMap and indirectly implements SortedMap interface. TreeMap also extends AbstractMap class.

    除了实现Map接口之外,Java TreeMap还实现了NavigableMap并间接实现了SortedMap 接口 。 TreeMap还扩展了AbstractMap类。
  2. TreeMap entries are sorted in the natural ordering of its keys. It also provides a constructor to provide Comparator to be used for ordering. So if you are using any class as key, make sure it’s implementing Comparable interface for natural ordering. Check out java collections interview questions to understand the importance of these methods.

    TreeMap条目按其键的自然顺序排序。 它还提供了一个构造函数,以提供用于排序的Comparator 。 因此,如果您使用任何类作为键,请确保其实现了Comparable接口以实现自然排序。 查看Java集合面试问题,以了解这些方法的重要性。
  3. Java TreeMap implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

    Java TreeMap实现为containsKey,get,put和remove操作提供了保证的log(n)时间成本。
  4. TreeMap is not synchronized and hence not thread-safe. For multithreaded environments, you can get a wrapped synchronized using Collections.synchronizedSortedMap method.

    TreeMap不同步,因此不是线程安全的。 对于多线程环境,可以使用Collections.synchronizedSortedMap方法获取包装的同步。
  5. TreeMap methods to get keyset and values return Iterator that are fail-fast in nature, so any concurrent modification will throw ConcurrentModificationException.

    用于获取键集和值的TreeMap方法返回本质上是快速失败的Iterator ,因此任何并发修改都会抛出ConcurrentModificationException
  6. TreeMap in java doesn’t allow null keys, however you can have multiple null values associated with different keys.

    Java中的TreeMap不允许使用空键,但是您可以将多个空值与不同的键关联。

Java TreeMap示例 (Java TreeMap Example)

Let’s look at java TreeMap example program to see it’s natural sorting in action.

让我们看一下Java TreeMap示例程序,看看它是自然排序的。

package com.journaldev.java;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class JavaTreeMapExample {

	public static void main(String[] args) {
		
		Map<Integer,String> map = new TreeMap<>();
		
		map.put(10, "10");
		map.put(1, "1");
		map.put(5, "5");
		
		System.out.println(map);
		
		map = new TreeMap<>(new Comparator<Integer>() {

			@Override
			public int compare(Integer x, Integer y) {
				return (x > y) ? -1 : ((x == y) ? 0 : 1);
			}
			
		});
		map.put(10, "10");
		map.put(1, "1");
		map.put(5, "5");
		System.out.println(map);

	}

}

It will produce below output.

它将产生以下输出。

{1=1, 5=5, 10=10}
{10=10, 5=5, 1=1}

Notice that when we are not providing Comparator while creating TreeMap, it’s using Integer compareTo method for ordering of keys. That’s why keys are in increasing order even though we insert it in any order.

请注意,当我们在创建TreeMap时未提供Comparator时,它使用Integer compareTo方法对键进行排序。 这就是即使我们按任意顺序插入键,键也按递增顺序排列的原因。

Next time, we are providing Comparator implementation to reverse the order and it’s being used by TreeMap. So the keys are stored in descending order.

下次,我们将提供Comparator实现来逆转顺序,TreeMap会使用该顺序。 因此,密钥以降序存储。

For simplicity, I am providing an anonymous class implementation of Comparator above, we can use lambda expressions to do the same in a single line.

为简单起见,我在上面提供了Comparator的匿名类实现,我们可以使用lambda表达式在同一行中执行相同的操作。

map = new TreeMap<>((x,y) -> {return (x > y) ? -1 : ((x == y) ? 0 : 1);});

TreeMap与HashMap (TreeMap vs HashMap)

TreeMap and HashMap both implements Map interface and part of collection framework. Let’s look at some of the differences between TreeMap vs HashMap.

TreeMap和HashMap都实现了Map接口和集合框架的一部分。 让我们看一下TreeMap与HashMap之间的一些区别。

  1. TreeMap entries are sorted in natural ordering of keys whereas HashMap doesn’t store entries in any order.

    TreeMap条目以键的自然顺序排序,而HashMap则不以任何顺序存储条目。
  2. TreeMap doesn’t allow null key whereas we can have one null key in HashMap.

    TreeMap不允许使用null键,而我们在HashMap中可以使用一个null键。
  3. Since TreeMap stores entries in sorted way, it’s a bit slower that HashMap in storing and retrieving objects.

    由于TreeMap以排序的方式存储条目,因此HashMap在存储和检索对象方面要慢一些。
  4. TreeMap uses Red-Black tree based NavigableMap implementation whereas HashMap uses hashing algorithm implementation.

    TreeMap使用基于Red-Black树的NavigableMap实现,而HashMap使用哈希算法实现。
  5. TreeMap implements NavigableMap, so you get some extra features that are not present in HashMap. For example – submap, first key, last key, head map, tail map etc.

    TreeMap实现了NavigableMap,因此您获得了HashMap中不存在的一些额外功能。 例如–子图,第一个键,最后一个键,头部图,尾部图等。

何时在Java中使用TreeMap (When to use TreeMap in Java)

Most of the time HashMap will be enough to use as Map implementation in your program. But if you have some special requirements related to sorting, finding next lower and higher key, work on a submap then you can go for TreeMap.

大多数时候,HashMap足以在您的程序中用作Map实现。 但是,如果您有一些与排序有关的特殊要求,查找下一个较低和较高的键,在子图上工作,则可以使用TreeMap。

Let’s look at a simple TreeMap example program showing usage of NavigableMap methods.

让我们看一个简单的TreeMap示例程序,该程序显示NavigableMap方法的用法。

package com.journaldev.java;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class JavaTreeMapNavigationExamples {

	public static void main(String[] args) {
		
		//we have to define object as TreeMap to use NavigableMap functions
		TreeMap<Integer,String> map = new TreeMap<>();
		for(int i=0;i<10;i++) {
			map.put(i, i+"");
		}
		
		System.out.println(map);
		
		//find id closest to 5, lower and higher
		Entry<Integer,String> entry = map.lowerEntry(5);
		System.out.println("Closest Lower key than 5 is "+entry);
		entry = map.higherEntry(5);
		System.out.println("Closest Higher key than 5 is "+entry);
		
		System.out.println("Closest Lower key than 4 is "+map.lowerKey(4));
		
		entry = map.floorEntry(5);
		System.out.println("Closest floor entry than 5 is "+entry);
		
		entry = map.ceilingEntry(4);
		System.out.println("Closest ceiling key than 4 is "+entry);
		
		entry = map.firstEntry();
		System.out.println("First Entry is "+entry);

		entry = map.lastEntry();
		System.out.println("Last Entry is "+entry);
		
		Map<Integer, String> reversedMap = map.descendingMap();
		System.out.println("Reversed Map: "+reversedMap);
		
		//poll and remove first, last entries
		entry = map.pollFirstEntry();
		System.out.println("First Entry is "+entry);
		entry = map.pollLastEntry();
		System.out.println("Last Entry is "+entry);
		System.out.println("Updated Map: "+map);
		
		//submap example
		Map<Integer, String> subMap = map.subMap(2, true, 6, true);
		System.out.println("Submap: "+subMap);
		
		subMap = map.headMap(5, true);
		System.out.println("HeadMap: "+subMap);

		subMap = map.tailMap(5, true);
		System.out.println("TailMap: "+subMap);
	}

}

When we execute above TreeMap example program, it produces following output.

当我们执行以上TreeMap示例程序时,它将产生以下输出。

{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}
Closest Lower key than 5 is 4=4
Closest Higher key than 5 is 6=6
Closest Lower key than 4 is 3
Closest floor entry than 5 is 5=5
Closest ceiling key than 4 is 4=4
First Entry is 0=0
Last Entry is 9=9
Reversed Map: {9=9, 8=8, 7=7, 6=6, 5=5, 4=4, 3=3, 2=2, 1=1, 0=0}
First Entry is 0=0
Last Entry is 9=9
Updated Map: {1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8}
Submap: {2=2, 3=3, 4=4, 5=5, 6=6}
HeadMap: {1=1, 2=2, 3=3, 4=4, 5=5}
TailMap: {5=5, 6=6, 7=7, 8=8}

All the above operations are self understood, please look into official documentation or comment here if you are confused about any of these.

以上所有操作都是可以理解的,如果对这些操作感到困惑,请查阅官方文档或在此处评论。

That’s all for a quick roundup for TreeMap in java, I hope you enjoyed reading it.

这就是Java中TreeMap的快速汇总,希望您喜欢阅读它。

References: Official API Documentation

参考: 官方API文档

翻译自: https://www.journaldev.com/14512/java-treemap-treemap-in-java

java中treemap

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值