当前位置:首页 » 编程语言 » java8遍历map

java8遍历map

发布时间: 2022-09-25 18:10:16

java中的map遍历有多种方法,从最早的iterator,到java5支持的foreach,再到java8 la

,前者效率更高

原因是for直接针对集合里的下一个对象

而iterator其实相当于是一个指针,这样说不准确,但是可以这样理解,每次执行它会先查找当前指向的对象,然后指针再指向下一个位置

所以说,如果有指针概念的话,for的“针对”直接是简单数据,而iterator的指针却是一个对象

⑵ java遍历map几种简单方法

代码如下:

importjava.util.HashMap;
importjava.util.Map;

publicclassApp{

publicstaticvoidmain(String[]args){

Map<String,Object>map=newHashMap<>();

map.put("Name","Barry");
map.put("Gender","Male");
map.put("Age",25);


//第一种遍历方式

for(Map.Entry<String,Object>entry:map.entrySet()){
System.out.println(entry.getKey()+"="+entry.getValue());
}

//第二种遍历方式

map.forEach((key,value)->{
System.out.println(key+"="+value);
});


//通过遍历key,然后再获取value

for(Stringkey:map.keySet()){
System.out.println(key+"="+map.get(key));
}

//单独遍历values

for(Objectvalue:map.values()){
System.out.println(value);
}
}
}

⑶ java7和java8对hashmap做了哪些优化

HashMap的原理介绍

此乃老生常谈,不作仔细解说。
一句话概括之:HashMap是一个散列表,它存储的内容是键值对(key-value)映射。

Java 7 中HashMap的源码分析

首先是HashMap的构造函数代码块1中,根据初始化的Capacity与loadFactor(加载因子)初始化HashMap.
//代码块1
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +loadFactor);

this.loadFactor = loadFactor;
threshold = initialCapacity;
init();
}

Java7中对于<key1,value1>的put方法实现相对比较简单,首先根据 key1 的key值计算hash值,再根据该hash值与table的length确定该key所在的index,如果当前位置的Entry不为null,则在该Entry链中遍历,如果找到hash值和key值都相同,则将值value覆盖,返回oldValue;如果当前位置的Entry为null,则直接addEntry。
代码块2
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}

modCount++;
addEntry(hash, key, value, i);
return null;
}

//addEntry方法中会检查当前table是否需要resize
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length); //当前map中的size 如果大于threshole的阈值,则将resize将table的length扩大2倍。
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}

createEntry(hash, key, value, bucketIndex);
}

Java7 中resize()方法的实现比较简单,将OldTable的长度扩展,并且将oldTable中的Entry根据rehash的标记重新计算hash值和index移动到newTable中去。代码如代码块3中所示,
//代码块3 --JDK7中HashMap.resize()方法
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}

Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}

/**
* 将当前table的Entry转移到新的table中
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}

HashMap性能的有两个参数:初始容量(initialCapacity) 和加载因子(loadFactor)。容量 是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。
根据源码分析可以看出:在Java7 中 HashMap的entry是按照index索引存储的,遇到hash冲突的时候采用拉链法解决冲突,将冲突的key和value插入到链表list中。
然而这种解决方法会有一个缺点,假如key值都冲突,HashMap会退化成一个链表,get的复杂度会变成O(n)。
在Java8中为了优化该最坏情况下的性能,采用了平衡树来存放这些hash冲突的键值对,性能由此可以提升至O(logn)。
代码块4 -- JDK8中HashMap中常量定义
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final int TREEIFY_THRESHOLD = 8; // 是否将list转换成tree的阈值
static final int UNTREEIFY_THRESHOLD = 6; // 在resize操作中,决定是否untreeify的阈值
static final int MIN_TREEIFY_CAPACITY = 64; // 决定是否转换成tree的最小容量
static final float DEFAULT_LOAD_FACTOR = 0.75f; // default的加载因子

在Java 8 HashMap的put方法实现如代码块5所示,
代码块5 --JDK8 HashMap.put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; //table为空的时候,n为table的长度
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null); // (n - 1) & hash 与Java7中indexFor方法的实现相同,若i位置上的值为空,则新建一个Node,table[i]指向该Node。
else {
// 若i位置上的值不为空,判断当前位置上的Node p 是否与要插入的key的hash和key相同
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;//相同则覆盖之
else if (p instanceof TreeNode)
// 不同,且当前位置上的的node p已经是TreeNode的实例,则再该树上插入新的node。
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 在i位置上的链表中找到p.next为null的位置,binCount计算出当前链表的长度,如果继续将冲突的节点插入到该链表中,会使链表的长度大于tree化的阈值,则将链表转换成tree。
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

再看下resize方法,由于需要考虑hash冲突解决时采用的可能是list 也可能是balance tree的方式,因此resize方法相比JDK7中复杂了一些,
代码块6 -- JDK8的resize方法
inal Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;//如果超过最大容量,无法再扩充table
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // threshold门槛扩大至2倍
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];// 创建容量为newCap的newTab,并将oldTab中的Node迁移过来,这里需要考虑链表和tree两种情况。

⑷ java8中如何动态遍历动态多维数组

有两种实现方法:

  • 可以用List数组来实现

  • 可以用map来实现

  • 方法一:用map来实现

    比如要创建一个1行、3列的数组,实现方法如下:

    public static void main(String[] args) throws CloneNotSupportedException { Map<Double, List<Double>> myMap = create(1, 3);}public static Map<Double, List<Double>> create(double row, double column) { Map<Double, List<Double>> doubleMap = new HashMap<Double, List<Double>>(); for (double x = 0; x < row; x++) { for (double y = 0; y < column; y++) { doubleMap.put(x, new ArrayList<Double>()); } } return doubleMap;}

    方法二:

    可以用List数组来实现

    publicstaticvoidmain(Stringargs[]){

    //list作为动态二维数组

    List<List<String>>list=newArrayList();

    List<String>a1=newArrayList<String>();

    List<String>a2=newArrayList<String>();

    List<String>a3=newArrayList<String>();

    list.add(a1);

    list.add(a2);

    list.add(a3);

    a1.add("string1ina1");

    a1.add("string2ina1");

    a2.add("string1ina2");

    a3.add("string1ina3");

    a3.add("string2ina3");

    for(inti=0;i<list.size();++i){

    for(intj=0;j<list.get(i).size();++j)

    System.out.println(list.get(i).get(j));

    }

    }

⑸ java8中,两个list<map>集合如何合并

这个简单呀,集合的长度是可变的,你把要合并的集合遍历出来,add( )添加到目标集合里就行了。

⑹ Java中便历Map的几种方法

  • 常见的Map遍历有下面四种方法:

importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map.Entry;

publicclassMapDemo{
publicstaticvoidmain(String[]args){
//准备好需要遍历的Map
HashMap<String,Integer>map=newHashMap<String,Integer>();
map.put("Tom",85);
map.put("Jack",97);
test1(map);
test2(map);
test3(map);
test4(map);

}

//方法一:迭代器方式
//特点:效率高,速度快,但是代码量多
publicstaticvoidtest1(HashMap<String,Integer>map){
Iterator<Entry<String,Integer>>it=map.entrySet().iterator();
while(it.hasNext()){
Entry<String,Integer>e=it.next();
System.out.println("name:"+e.getKey()+" score:"+e.getValue());
}
}

//方法二:map.entrySet()for循环
//特点:效率也较高,速度较快,且写法比方法一简单
publicstaticvoidtest2(HashMap<String,Integer>map){
for(Entry<String,Integer>e:map.entrySet()){
System.out.println("name:"+e.getKey()+" score:"+e.getValue());
}
}

//方法3map.keySetfor循环
// 特点:效率较慢
publicstaticvoidtest3(HashMap<String,Integer>map){
for(Stringkey:map.keySet()){
System.out.println("name:"+key+" score:"+map.get(key));
}
}

//方法四:forEach
//特点速度较慢,但是代码少,简洁;(需要Java8或以上版本的支持)
publicstaticvoidtest4(HashMap<String,Integer>map){
map.forEach((k,v)->System.out.println("name:"+k+" score:"+v));
}
}

四种方法之间的效率比较

(test1≈test2)>(test3≈test4)

推荐: 数据量特别大的时候 使用方法1: 代码长,但是效率高

数据量较少的, 那么使用方法4: 代码简洁而优雅~

⑺ Java里Map接口的实现类HashMap在遍历时用到的EntrySet不理解为什么要这么用

遍历的对象必须是数组或实现Iterable接口
HashMap 没有实现 Iterable 接口!
而EnetrySet 返回 一个Set 实现了Iterable 接口

⑻ java如何遍历map的所有的元素

package net.nie.test; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapTest { private static Map<Integer, String> map=new HashMap<Integer,String>(); /** 1.HashMap 类映射不保证顺序;某些映射可明确保证其顺序: TreeMap 类 * 2.在遍历Map过程中,不能用map.put(key,newVal),map.remove(key)来修改和删除元素, * 会引发 并发修改异常,可以通过迭代器的remove(): * 从迭代器指向的 collection 中移除当前迭代元素 * 来达到删除访问中的元素的目的。 * */ public static void main(String[] args) { map.put(1,"one"); map.put(2,"two"); map.put(3,"three"); map.put(4,"four"); map.put(5,"five"); map.put(6,"six"); map.put(7,"seven"); map.put(8,"eight"); map.put(5,"five"); map.put(9,"nine"); map.put(10,"ten"); Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<Integer, String> entry=it.next(); int key=entry.getKey(); if(key%2==1){ System.out.println("delete this: "+key+" = "+key); //map.put(key, "奇数"); // //map.remove(key); // it.remove(); //OK } } //遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。 System.out.println("-------nt最终的map的元素遍历:"); for(Map.Entry<Integer, String> entry:map.entrySet()){ int k=entry.getKey(); String v=entry.getValue(); System.out.println(k+" = "+v); } } }

⑼ Java中怎么遍历map中value值

Java中遍历Map对象的4种方法:

1、通过Map.entrySet遍历key和value,在for-each循环中使用entries来遍历.推荐,尤其是容量大时。

(9)java8遍历map扩展阅读:

关于JAVA的遍历知识补充:

1、list和set集合都实现了Iterable接口,所以他们的实现类可以使用迭代器遍历,map集合未实现该接口,若要使用迭代器循环遍历,需要借助set集合。

2、使用EntrySet 遍历,效率更高。

⑽ Java8,stream().map().collect(Collectors.toList()).forEach()和stream().map().forEach()有啥区别

在stream().map().collect(Collectors.toList()).forEach()中,你的forEach()针对的List;而
stream().map().forEach()针对的是Stream流。从结果操作来看是一样的,中间过程回产生一些临时变量。

热点内容
左游手柄助手2脚本 发布:2024-05-19 11:40:28 浏览:1001
挖矿需要什么配置 发布:2024-05-19 11:38:02 浏览:894
eclipse导出ant脚本 发布:2024-05-19 11:20:28 浏览:98
如何改变vivo手机账户密码 发布:2024-05-19 10:56:07 浏览:376
sql的length函数 发布:2024-05-19 10:55:15 浏览:545
数据库管理系统设计报告 发布:2024-05-19 10:49:50 浏览:684
linux怎么将驱动编译进内核 发布:2024-05-19 10:23:47 浏览:768
c语言读程序题 发布:2024-05-19 10:13:52 浏览:675
新的安卓手机怎么样下载微信 发布:2024-05-19 10:05:06 浏览:879
加9的算法 发布:2024-05-19 10:04:15 浏览:264