Java map集合順序如何同步添加順序
更新時間:2020年04月03日 10:32:55 作者:安,財
這篇文章主要介紹了Java map集合順序如何同步添加順序,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
一般使用map用的最多的就是hashmap,但是hashmap里面的元素是不按添加順序的,那么除了使用hashmap外,還有什么map接口的實現(xiàn)類可以用呢?
這里有2個,treeMap和linkedHashMap,但是,要達(dá)到我們的要求:按添加順序保存元素的,就只有LinkedHashMap。
下面看運行的代碼。
package com.lxk.collectionTest; import com.google.common.collect.Maps; import java.util.Map; /** * 測試Map是否有序的區(qū)別 * <p> * Created by lxk on 2017/5/24 */ public class OrderedMapTest { public static void main(String[] args) { Map<String, Integer> hashMap = Maps.newHashMap(); Map<String, Integer> treeMap = Maps.newTreeMap(); Map<String, Integer> linkedHashMap = Maps.newLinkedHashMap(); System.out.println("--------------test hashMap"); testMap(hashMap); System.out.println("--------------test treeMap"); testMap(treeMap); System.out.println("--------------test linkedHashMap"); testMap(linkedHashMap); } private static void testMap(Map<String, Integer> map) { map.put("asd", 1); map.put("2das", 2); map.put("3das", 3); map.put("4das", 4); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java短網(wǎng)址服務(wù)(TinyURL)生成算法
這篇文章主要為大家詳細(xì)介紹了java短網(wǎng)址服務(wù)生成算法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08SpringBoot2 整合FreeMarker實現(xiàn)頁面靜態(tài)化示例詳解
這篇文章主要介紹了SpringBoot2 整合FreeMarker實現(xiàn)頁面靜態(tài)化示例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07SpringBoot中實現(xiàn)分布式的Session共享的詳細(xì)教程
這篇文章主要介紹了SpringBoot中實現(xiàn)分布式的Session共享,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06