Java中的树映射

Java中的树映射用于实现 地图界面 导航地图 以及AbstractMap类。地图是按照其键的自然顺序排序的,或者按照 比较器 在地图创建时提供,具体取决于使用的构造函数。这被证明是排序和存储键值对的有效方法。树映射维护的存储顺序必须与equals保持一致,就像任何其他排序映射一样,无论显式比较器如何。treemap实现是不同步的,因为如果一个映射由多个线程并发访问,并且至少有一个线程在结构上修改映射,那么它必须在外部同步。

null

图片[1]-Java中的树映射-yiteyi-C++库

树形图的特征

树状图的一些重要特征如下:

  1. 这个班是 Java集合 框架
  2. 该类实现 映射接口 包括…在内 导航地图 , 分类地图 ,并扩展了AbstractMap类。
  3. Java中的TreeMap不允许空键(比如Map),因此 空指针异常 被扔了。但是,多个空值可以与不同的键相关联。
  4. 此类中的方法及其视图返回的条目对表示生成映射时的快照。他们不支持 进入设定值 方法

现在让我们继续讨论同步树形图。 树映射的实现是不同步的。这意味着,如果多个线程同时访问一个树集,并且至少有一个线程修改了该树集,那么它必须在外部同步。这通常通过使用 收藏。同步分类地图 方法这最好在创建时完成,以防止意外不同步地访问集合。这可以通过以下方式实现:

SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...)); 

极客们,现在你们一定想知道TreemMap在内部是如何工作的?

树映射中的方法在获取键集和值时,返回一个本质上是快速失败的迭代器。因此,任何并发修改都将抛出 ConcurrentModificationException .树形图基于红黑颜色 数据结构。

树中的每个节点都有:

  • 3个变量( K键=键,V值=值,布尔颜色=颜色 )
  • 3参考文献( 条目左=左,条目右=右,条目父=父 )

树映射中的构造函数

为了创建TreeMap,我们需要创建TreeMap类的对象。TreeMap类由各种构造函数组成,这些构造函数允许创建TreeMap。以下是该类中可用的构造函数:

  1. 树映射()
  2. 树映射(比较器comp)
  3. 树形图(地图M)
  4. 树地图(分类地图sm)

让我们在实现每个构造函数的同时单独讨论它们,如下所示:

建造师1: 树映射()

此构造函数用于构建一个空树映射,该树映射将使用其键的自然顺序进行排序。

实例

JAVA

// Java Program to Demonstrate TreeMap
// using the Default Constructor
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
// Main class
// TreeMapImplementation
public class GFG {
// Method 1
// To show TreeMap constructor
static void Example1stConstructor()
{
// Creating an empty TreeMap
TreeMap<Integer, String> tree_map
= new TreeMap<Integer, String>();
// Mapping string values to int keys
// using put() method
tree_map.put( 10 , "Geeks" );
tree_map.put( 15 , "4" );
tree_map.put( 20 , "Geeks" );
tree_map.put( 25 , "Welcomes" );
tree_map.put( 30 , "You" );
// Printing the elements of TreeMap
System.out.println( "TreeMap: " + tree_map);
}
// Method 2
// Main driver method
public static void main(String[] args)
{
System.out.println( "TreeMap using "
+ "TreeMap() constructor:" );
// Calling constructor
Example1stConstructor();
}
}


输出:

TreeMap using TreeMap() constructor:TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}

建造师2: 树映射(比较器comp)

此构造函数用于构建一个空的TreeMap对象,其中的元素需要排序顺序的外部规范。

实例

JAVA

// Java Program to Demonstrate TreeMap
// using Comparator Constructor
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
// Class 1
// Helper class representing Student
class Student {
// Attributes of a student
int rollno;
String name, address;
// Constructor
public Student( int rollno, String name, String address)
{
// This keyword refers to current object itself
this .rollno = rollno;
this .name = name;
this .address = address;
}
// Method of this class
// To print student details
public String toString()
{
return this .rollno + " " + this .name + " "
+ this .address;
}
}
// Class 2
// Helper class - Comparator implementation
class Sortbyroll implements Comparator<Student> {
// Used for sorting in ascending order of
// roll number
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}
// Class 3
// Main class
public class GFG {
// Calling constructor inside main()
static void Example2ndConstructor()
{
// Creating an empty TreeMap
TreeMap<Student, Integer> tree_map
= new TreeMap<Student, Integer>(
new Sortbyroll());
// Mapping string values to int keys
tree_map.put( new Student( 111 , "bbbb" , "london" ), 2 );
tree_map.put( new Student( 131 , "aaaa" , "nyc" ), 3 );
tree_map.put( new Student( 121 , "cccc" , "jaipur" ), 1 );
// Printing the elements of TreeMap
System.out.println( "TreeMap: " + tree_map);
}
// Main driver method
public static void main(String[] args)
{
System.out.println( "TreeMap using "
+ "TreeMap(Comparator)"
+ " constructor:" );
Example2ndConstructor();
}
}


输出:

TreeMap using TreeMap(Comparator) constructor:TreeMap: {111 bbbb london=2, 121 cccc jaipur=1, 131 aaaa nyc=3}

建造师3: 树形图(地图M)

该构造函数用于初始化一个树映射,其中包含给定映射M中的条目,这些条目将使用键的自然顺序进行排序。

实例

JAVA

// Java Program to Demonstrate TreeMap
// using the Default Constructor
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
// Main class
public class TreeMapImplementation {
// Method 1
// To illustrate constructor<Map>
static void Example3rdConstructor()
{
// Creating an empty HashMap
Map<Integer, String> hash_map
= new HashMap<Integer, String>();
// Mapping string values to int keys
// using put() method
hash_map.put( 10 , "Geeks" );
hash_map.put( 15 , "4" );
hash_map.put( 20 , "Geeks" );
hash_map.put( 25 , "Welcomes" );
hash_map.put( 30 , "You" );
// Creating the TreeMap using the Map
TreeMap<Integer, String> tree_map
= new TreeMap<Integer, String>(hash_map);
// Printing the elements of TreeMap
System.out.println( "TreeMap: " + tree_map);
}
// Method 2
// Main driver method
public static void main(String[] args)
{
System.out.println( "TreeMap using "
+ "TreeMap(Map)"
+ " constructor:" );
Example3rdConstructor();
}
}


输出:

TreeMap using TreeMap(Map) constructor:TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}

建造师4: 树地图(分类地图sm)

此构造函数用于使用给定 分类地图 它将以与给定的排序地图相同的顺序存储。

实例

JAVA

// Java Program to Demonstrate TreeMap
// using the SortedMap Constructor
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
// Main class
// TreeMapImplementation
public class GFG {
// Method
// To show TreeMap(SortedMap) constructor
static void Example4thConstructor()
{
// Creating a SortedMap
SortedMap<Integer, String> sorted_map
= new ConcurrentSkipListMap<Integer, String>();
// Mapping string values to int keys
// using put() method
sorted_map.put( 10 , "Geeks" );
sorted_map.put( 15 , "4" );
sorted_map.put( 20 , "Geeks" );
sorted_map.put( 25 , "Welcomes" );
sorted_map.put( 30 , "You" );
// Creating the TreeMap using the SortedMap
TreeMap<Integer, String> tree_map
= new TreeMap<Integer, String>(sorted_map);
// Printing the elements of TreeMap
System.out.println( "TreeMap: " + tree_map);
}
// Method 2
// Main driver method
public static void main(String[] args)
{
System.out.println( "TreeMap using "
+ "TreeMap(SortedMap)"
+ " constructor:" );
Example4thConstructor();
}
}


输出:

TreeMap using TreeMap(SortedMap) constructor:TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}

TreeMap类中的方法

方法 执行的动作
清除() 该方法从该树映射中删除所有映射并清除映射。
克隆() 该方法返回此树映射的浅层副本。
containsKey(对象键) 如果此映射包含指定键的映射,则返回true。
containsValue(对象值) 如果此映射将一个或多个键映射到指定值,则返回true。
入口集() 返回此映射中包含的映射的集合视图。
firstKey() 返回此排序映射中当前的第一个(最低)键。
获取(对象键) 返回此映射映射到指定键的值。
人头图(对象键值) 该方法返回的映射部分视图严格小于参数key_值。
键集() 该方法返回树映射中包含的键的集合视图。
lastKey() 返回此排序映射中当前的最后一个(最高)键。
put(对象键、对象值) 该方法用于将贴图插入贴图中。
putAll(地图) 将指定映射中的所有映射复制到此映射。
移除(对象键) 从树映射中删除此键的映射(如果存在)。
大小() 返回此映射中的键值映射数。
子映射((K开始键,K结束键) 该方法返回该映射中键范围从startKey(包含)到endKey(独占)的部分。
价值观() 返回此映射中包含的值的集合视图。

实施: 下面的程序将更好地演示如何创建、插入和遍历树形图。

插图:

JAVA

// Java Program to Illustrate Operations in TreeMap
// Such as Creation, insertion
// searching, and traversal
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
// Main class
// Implementation of TreeMap
public class GFG {
// Declaring a TreeMap
static TreeMap<Integer, String> tree_map;
// Method 1
// To create TreeMap
static void create()
{
// Creating an empty TreeMap
tree_map = new TreeMap<Integer, String>();
// Display message only
System.out.println( "TreeMap successfully"
+ " created" );
}
// Method 2
// To Insert values in the TreeMap
static void insert()
{
// Mapping string values to int keys
// using put() method
tree_map.put( 10 , "Geeks" );
tree_map.put( 15 , "4" );
tree_map.put( 20 , "Geeks" );
tree_map.put( 25 , "Welcomes" );
tree_map.put( 30 , "You" );
// Display message only
System.out.println( "Elements successfully"
+ " inserted in the TreeMap" );
}
// Method 3
// To search a key in TreeMap
static void search( int key)
{
// Checking for the key
System.out.println( "Is key "" + key
+ "" present? "
+ tree_map.containsKey(key));
}
// Method 4
// To search a value in TreeMap
static void search(String value)
{
// Checking for the value
System.out.println( "Is value "" + value
+ "" present? "
+ tree_map.containsValue(value));
}
// Method 5
// To display the elements in TreeMap
static void display()
{
// Displaying the TreeMap
System.out.println( "Displaying the TreeMap:" );
System.out.println( "TreeMap: " + tree_map);
}
// Method 6
// To traverse TreeMap
static void traverse()
{
// Display message only
System.out.println( "Traversing the TreeMap:" );
for (Map.Entry<Integer, String> e :
tree_map.entrySet())
System.out.println(e.getKey() + " "
+ e.getValue());
}
// Method 6
// Main driver method
public static void main(String[] args)
{
// Calling above defined methods inside main()
// Creating a TreeMap
create();
// Inserting the values in the TreeMap
insert();
// Search key "50" in the TreeMap
search( 50 );
// Search value "Geeks" in the TreeMap
search( "Geeks" );
// Display the elements in TreeMap
display();
// Traversing the TreeMap
traverse();
}
}


输出:

TreeMap successfully createdElements successfully inserted in the TreeMapIs key "50" present? falseIs value "Geeks" present? trueDisplaying the TreeMap:TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}Traversing the TreeMap:10 Geeks15 420 Geeks25 Welcomes30 You

在TreeMap上执行各种操作

在Java 1.5中引入泛型之后,可以限制可以存储在树映射中的对象类型。现在,让我们看看如何在树映射上执行一些常用的操作。

操作1: 添加元素

为了向树映射添加元素,我们可以使用 put()方法 .但是,树映射中不保留插入顺序。在内部,每个元素的键都会按升序进行比较和排序。

实例

JAVA

// Java Program to Illustrate Addition of Elements
// in TreeMap using put() Method
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Default Initialization of a TreeMap
TreeMap tm1 = new TreeMap();
// Inserting the elements in TreeMap
// using put() method
tm1.put( 3 , "Geeks" );
tm1.put( 2 , "For" );
tm1.put( 1 , "Geeks" );
// Initialization of a TreeMap using Generics
TreeMap<Integer, String> tm2
= new TreeMap<Integer, String>();
// Inserting the elements in TreeMap
// again using put() method
tm2.put( new Integer( 3 ), "Geeks" );
tm2.put( new Integer( 2 ), "For" );
tm2.put( new Integer( 1 ), "Geeks" );
// Printing the elements of both TreeMaps
// Map 1
System.out.println(tm1);
// Map 2
System.out.println(tm2);
}
}


输出:

{1=Geeks, 2=For, 3=Geeks}{1=Geeks, 2=For, 3=Geeks}

操作2:改变元素

在添加元素之后,如果我们希望更改元素,可以通过再次添加带有 put()方法 .由于树状图中的元素使用键进行索引,因此只需插入我们希望更改的键的更新值,即可更改键的值。

实例

JAVA

// Java program to Illustrate Updation of Elements
// in TreeMap using put() Method
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Initialization of a TreeMap
// using Generics
TreeMap<Integer, String> tm
= new TreeMap<Integer, String>();
// Inserting the elements in Map
// using put() method
tm.put( 3 , "Geeks" );
tm.put( 2 , "Geeks" );
tm.put( 1 , "Geeks" );
// Print all current elements in map
System.out.println(tm);
// Inserting the element at specified
// corresponding to specified key
tm.put( 2 , "For" );
// Printing the updated elements of Map
System.out.println(tm);
}
}


输出:

{1=Geeks, 2=Geeks, 3=Geeks}{1=Geeks, 2=For, 3=Geeks}

操作3: 移除元素

为了从树映射中删除元素,我们可以使用 remove()方法 。此方法获取密钥值,并从该树状图中删除密钥的映射(如果该映射存在于映射中)。

实例

JAVA

// Java program to Illustrate Removal of Elements
// in TreeMap using remove() Method
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Initialization of a TreeMap
// using Generics
TreeMap<Integer, String> tm
= new TreeMap<Integer, String>();
// Inserting the elements
// using put() method
tm.put( 3 , "Geeks" );
tm.put( 2 , "Geeks" );
tm.put( 1 , "Geeks" );
tm.put( 4 , "For" );
// Printing all elements of Map
System.out.println(tm);
// Removing the element corresponding to key
tm.remove( 4 );
//  Printing updated TreeMap
System.out.println(tm);
}
}


输出:

{1=Geeks, 2=Geeks, 3=Geeks, 4=For}{1=Geeks, 2=Geeks, 3=Geeks}

操作4: 遍历树映射

有多种方法可以遍历地图。最著名的方法是使用 对于每个循环 拿到钥匙。通过使用 getValue()方法 .

实例

JAVA

// Java Program to Illustrate Iterating over TreeMap
// using
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Initialization of a TreeMap
// using Generics
TreeMap<Integer, String> tm
= new TreeMap<Integer, String>();
// Inserting the elements
// using put() method
tm.put( 3 , "Geeks" );
tm.put( 2 , "For" );
tm.put( 1 , "Geeks" );
// For-each loop for traversal over Map
// via entrySet() Method
for (Map.Entry mapElement : tm.entrySet()) {
int key = ( int )mapElement.getKey();
// Finding the value
String value = (String)mapElement.getValue();
// Printing the key and value
System.out.println(key + " : " + value);
}
}
}


输出:

1 : Geeks2 : For3 : Geeks

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享