首页 > 编程语言 >java 用 Java 将 HashMap 转换为 TreeMap 的程序

java 用 Java 将 HashMap 转换为 TreeMap 的程序

时间:2023-04-19 15:57:36浏览次数:59  
标签:Map Java hashMap treeMap TreeMap HashMap

转载自:https://www.moonapi.com/news/24923.html

 

HashMap 是 Java 1.2 以来 Java 集合的一部分。它提供了以(键、值)对存储数据的 Java Map 接口的基本实现。要访问 HashMap 中的值,必须知道它的键。哈希映射被称为哈希映射,因为它使用哈希技术来存储数据。

Java 中的树图和抽象类一起用来实现地图接口和导航地图。地图根据其关键字的自然顺序进行排序,或者由地图创建时提供的比较器进行排序,具体取决于使用的构造函数。这被证明是排序和存储键值对的有效方式。

下面是在 Java 中将 HashMap 转换成 TreeMap 的方法,这样得到的 TreeMap 应该包含 HashMap 的所有映射,按照它们的键的自然顺序排序。

示例:

输入:HashMap:{ 1 =极客,2 =伪造者,3 =计算机门户} T3】输出:树形图:{ 1 =极客,2 =伪造者,3 =计算机门户}

输入:哈希表:{1=1,2=2,3=3} 输出:树形图:{1=1,2=2,3=3}

以下是在 Java 中将 HashMap 转换为 TreeMap 的方法:

1。在 Java 8 中:这个方法包括将 HashMap 转换为 Stream,并使用 Stream.collect()方法收集 TreeMap 中的流元素,该方法接受一个收集器。

算法:

  1. 获取要转换的 HashMap。
  2. 从哈希表中获取条目
  3. 将地图条目转换为流
  4. 使用收集器,收集条目并将其转换为树形图
  5. 现在收集树形图
  6. 返回形成的树形图

程序:

Java 语言(一种计算机语言,尤用于创建网站)

// Java Program to convert
// HashMap to TreeMap in Java 8

import java.util.*;
import java.util.stream.*;

class GFG {

    // Generic function to construct a new 
    // TreeMap from HashMap
    public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap)
    {
        Map<K, V>
            treeMap = hashMap
                          // Get the entries from the hashMap
                          .entrySet()

                          // Convert the map into stream
                          .stream()

                          // Now collect the returned TreeMap
                          .collect(
                              Collectors

                                  // Using Collectors, collect the entries
                                  // and convert it into TreeMap
                                  .toMap(
                                      Map.Entry::getKey,
                                      Map.Entry::getValue,
                                      (oldValue,
                                       newValue)
                                          -> newValue,
                                      TreeMap::new));

        // Return the TreeMap
        return treeMap;
    }

    public static void main(String args[])
    {
        // Create a HashMap
        Map<String, String> hashMap = new HashMap<>();

        // Add entries to the HashMap
        hashMap.put("1", "Geeks");
        hashMap.put("2", "forGeeks");
        hashMap.put("3", "A computer Portal");

        // Print the HashMap
        System.out.println("HashMap: " + hashMap);

        // construct a new TreeMap from HashMap
        Map<String, String> treeMap = convertToTreeMap(hashMap);

        // Print the TreeMap
        System.out.println("TreeMap: " + treeMap);
    }
}

输出:

HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}

2。使用纯 Java :在这个方法中,要么将 HashMap 实例传递给 TreeMap 构造函数,要么传递给 putAll()方法。这将直接从哈希表创建树形图。

算法:

  1. 获取要转换的 HashMap。
  2. 创建新的树形图
  3. 将 hashMap 传递给 treeMap 的 putAll()方法
  4. 返回形成的树形图

程序:

Java 语言(一种计算机语言,尤用于创建网站)

// Java Program to convert
// HashMap to TreeMap in Java 8

import java.util.*;
import java.util.stream.*;

class GFG {

    // Generic function to construct a 
    // new TreeMap from HashMap
    public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap)
    {
        // Create a new TreeMap
        Map<K, V> treeMap = new TreeMap<>();

        // Pass the hashMap to putAll() method
        treeMap.putAll(hashMap);

        // Return the TreeMap
        return treeMap;
    }

    public static void main(String args[])
    {
        // Create a HashMap
        Map<String, String> hashMap = new HashMap<>();

        // Add entries to the HashMap
        hashMap.put("1", "Geeks");
        hashMap.put("2", "forGeeks");
        hashMap.put("3", "A computer Portal");

        // Print the HashMap
        System.out.println("HashMap: " + hashMap);

        // construct a new TreeMap from HashMap
        Map<String, String> treeMap = convertToTreeMap(hashMap);

        // Print the TreeMap
        System.out.println("TreeMap: " + treeMap);
    }
}

输出:

HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}

3。使用谷歌的番石榴库:番石榴还提供了一个树形图实现,可以用来创建一个空的树形图实例。

算法:

  1. 获取要转换的 HashMap。
  2. 使用番石榴库的 Maps.newTreeMap()创建新的树图
  3. 将 hashMap 传递给 treeMap 的 putAll()方法
  4. 返回形成的树形图

程序:

Java 语言(一种计算机语言,尤用于创建网站)

// Java Program to convert
// HashMap to TreeMap in Java 8

import com.google.common.collect.*;
import java.util.*;
import java.util.stream.*;

class GFG {

    // Generic function to construct a
    // new TreeMap from HashMap
    public static <K extends Comparable, V> Map<K, V> 
                       convertToTreeMap(Map<K, V> hashMap)
    {
        // Create a new TreeMap
        Map<K, V> treeMap = Maps.newTreeMap();

        // Pass the hashMap to putAll() method
        treeMap.putAll(hashMap);

        // Return the TreeMap
        return treeMap;
    }

    public static void main(String args[])
    {
        // Create a HashMap
        Map<String, String> hashMap = new HashMap<>();

        // Add entries to the HashMap
        hashMap.put("1", "Geeks");
        hashMap.put("2", "forGeeks");
        hashMap.put("3", "A computer Portal");

        // Print the HashMap
        System.out.println("HashMap: " + hashMap);

        // construct a new TreeMap from HashMap
        Map<String, String> treeMap = convertToTreeMap(hashMap);

        // Print the TreeMap
        System.out.println("TreeMap: " + treeMap);
    }
}

输出:

HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}

4。不兼容类型之间的转换:如果所需的树形图与 HashMap 的类型不同,可以使用该方法。在这种情况下,转换需要手动完成。

算法:

  1. 获取要转换的 HashMap。
  2. 创建新的树形图
  3. 对于哈希表的每个条目:
    • 通过转换将键和值转换为所需的类型
    • 通过 treeMap 的 put()方法插入转换后的对
  4. 返回形成的树形图

程序:

Java 语言(一种计算机语言,尤用于创建网站)

// Java Program to convert
// HashMap to TreeMap in Java 8

import java.util.*;
import java.util.stream.*;

class GFG {

    // Function to construct a new TreeMap from HashMap
    public static Map<Integer, String> 
               convertToTreeMap(Map<String, String> hashMap)
    {
        // Create a new TreeMap
        Map<Integer, String> treeMap = new TreeMap<>();

        // Convert the HashMap to TreeMap manually
        for (Map.Entry<String, String> e : hashMap.entrySet()) {
            treeMap.put(Integer.parseInt(e.getKey()), e.getValue());
        }

        // Return the TreeMap
        return treeMap;
    }

    public static void main(String args[])
    {
        // Create a HashMap
        Map<String, String> hashMap = new HashMap<>();

        // Add entries to the HashMap
        hashMap.put("1", "Geeks");
        hashMap.put("2", "forGeeks");
        hashMap.put("3", "A computer Portal");

        // Print the HashMap
        System.out.println("HashMap: " + hashMap);

        // construct a new TreeMap<Integer, String>
        // from HashMap<String, String>
        Map<Integer, String> treeMap = convertToTreeMap(hashMap);

        // Print the TreeMap
        System.out.println("TreeMap: " + treeMap);
    }
}

输出:

HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}

标签:Map,Java,hashMap,treeMap,TreeMap,HashMap
From: https://www.cnblogs.com/zhncnblogs/p/17333565.html

相关文章

  • Linux课程(大数据、JavaEE,Python通用版)
    尚硅谷Linux课程(大数据、JavaEE,Python通用版)整理:韩顺平Linux课程笔记第1章LINUX开山篇1.1本套LINUX课程的内容介绍1.2LINUX的学习方向1.2.1Linux运维工程师.1.2.2Linux嵌入式开发工程师.123在linux下做各种程序开发.1.2.4示意图.1.3LINUX的应用领域......
  • java jdk 国内下载镜像地址及安装
      javajdk国内下载镜像地址(1)TUNA镜像 https://mirrors.tuna.tsinghua.edu.cn/AdoptOpenJDK/(2)HUAWEI镜像 https://repo.huaweicloud.com/java/jdk/安装一、手动解压安装包:1、在user目录下新建java文件夹:#cd/usr/#mkdirjava#cdjava2.下载jdk1.8#wgethttp:......
  • java 通过url下载附件并压缩zip
    publicFilezipAttachFile(StringfilePathDir,List<String>urlFileList,StringmemberId)throwsException{filePathDir="/home/file";FilezipFileDir=newFile(filePathDir);if(!zipFileDir.exists()){......
  • java 删除文件和目录
    publicvoiddeleteFileAndDir(StringfilePathDir){Pathpath=Paths.get(filePathDir);try{Files.walkFileTree(path,newSimpleFileVisitor<Path>(){//先去遍历删除文件......
  • windows下安装java环境粗糙步骤——博客园
    下载安装1.首先下载jdk安装包  官网下载:https://www.oracle.com/java/technologies/downloads/#jdk20-windows 百度云盘:链接:https://pan.baidu.com/s/1DpF83y-CDAgnGKdbmlvpxw?pwd=BS11提取码:BS11 2.安装双击下载好的安装包,点击下一步,傻瓜式安装方式进行,中间记......
  • M2 java 反编译工具 jd-gui安装
    安装java1.8验证安装whichjava$(/usr/libexec/java_home)echo$JAVA_HOMEjava-verison```####brew安装brewinstalljd-gui###已经安装jdk1.8但是Java反编译工具JD-GUI还是报错找不到java1.8+ERRORlaunching'JD-GUI'NosuitableJavaversionfoundon......
  • 程序之外的java文件
      ......
  • Java SpringBoot 加载 yml 配置文件中字典项
    将字典数据,配置在yml文件中,通过加载yml将数据加载到Map中SpringBoot中yml配置、引用其它yml中的配置。#在配置文件目录(如:resources)下新建application-xxx必须以application开头的yml文件,多个文件用","号分隔,不能换行项目结构文件application.ymlserver:po......
  • 设计模式-模板模式在Java中的使用示例-悍马模型制造示例
    场景设计模式-模板模式在Java中的使用示例:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/130230732上面整理了模板模式的使用示例,为加强理解特记录另一个使用示例,以下示例摘自设计模式之禅第二版。模板方法模式定义一个操作中的算法的框架,而将一些步骤延迟到......
  • 每日八股文之Java
    1、请你说说死锁定义及发生的条件得分点:争夺共享资源、相互等待、互斥条件、请求和保持条件、不剥夺条件、环路等待条件死锁定义:两个或两个以上的进程在执行过程中,因争夺共享资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或......