Java HashMap进行遍历的几种方式

简介: Java HashMap进行遍历的几种方式
package hashMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;
public class mapTest {
  @SuppressWarnings("unused")
  public static void main(String[] args) {
    Map<Integer, String> a = new HashMap<Integer, String>();
    a.put(11, "Jerry");
    a.put(22, "Tom");
    a.put(33, "Jim");
    Collection<String> valueCollection =  a.values();
    // features.forEach(System.out::println);
    for( String item : valueCollection){ 
      System.out.println("value in HashMap: " + item);
    }
    for (Entry<Integer, String> entry : a.entrySet()) {
        System.out.println(entry.getKey() + " - " + entry.getValue());
    }
//    Java8 Streams & Lambda expressions demo     
//    productOrderQuantityMap = CachedDB
    Stream<String> filterResult = a.values().stream().filter( b -> b.equals("Jerry"));
    filterResult.forEach(System.out::println); // only return Jerry
    /* (params) -> expression
    (params) -> statement
    (params) -> { statements } */
    /* if you are working on a closed stream, you will meet with error below:
     * Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
  at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
  at java.util.stream.ReferencePipeline.forEach(Unknown Source)
  at hashMap.mapTest.main(mapTest.java:37)
     */
    // filterResult.forEach( (each) -> System.out.println("filter result: " + each ));
    /* Returns an equivalent stream that is parallel. May return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel. 
This is an intermediate operation.
Returns:a parallel stream
     */
    Stream<Map.Entry<Integer, String>> newStream = a.entrySet().stream().parallel();
    System.out.println("Count: " + newStream.count()); // 3
    /* 
     * Returns a stream consisting of the results of replacing each element of this 
     * stream with the contents of a mapped stream produced by applying the provided 
     * mapping function to each element. Each mapped stream is 
     * closed after its contents have been placed into this stream. 
     * (If a mapped stream is null an empty stream is used, instead.) 
      This is an intermediate operation.
      Parameters:<R> The element type of the new streammapper a non-interfering, stateless function to apply to each element which produces a stream of new valuesReturns:the new stream@apiNoteThe flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the resulting elements into a new stream. 
      Examples. 
      If orders is a stream of purchase orders, and each purchase order contains a collection of line items, then the following produces a stream containing all the line items in all the orders: 
orders.flatMap(order -> order.getLineItems().stream())...
If path is the path to a file, then the following produces a stream of the words contained in that file: 
Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8);
     Stream<String> words = lines.flatMap(line -> Stream.of(line.split(" +")));
The mapper function passed to flatMap splits a line, using a simple regular expression, into an array of words, and then creates a stream of words from that array.
     */
//        .getPurchaseOrderMap()
//        .values()
//        .stream()
//        .parallel()
//        .flatMap(
//            po -> po.getProductQuantityMap().entrySet()
//                .stream())
//        .collect(
//            Collectors.groupingBy(
//                t -> t.getKey(),
//                Collectors
//                    .summingInt(t -> ((Entry<Integer, Integer>) t)
//                        .getValue())));
  }
}


相关文章
|
13天前
|
设计模式 Java
结合HashMap与Java 8的Function和Optional消除ifelse判断
`shigen`是一位致力于记录成长、分享认知和留住感动的博客作者。本文通过具体代码示例探讨了如何优化业务代码中的if-else结构。首先展示了一个典型的if-else处理方法,并指出其弊端;然后引入了策略模式和工厂方法等优化方案,最终利用Java 8的Function和Optional特性简化代码。此外,还提到了其他几种消除if-else的方法,如switch-case、枚举行、SpringBoot的IOC等。一起跟随shigen的脚步,让每一天都有所不同!
28 10
结合HashMap与Java 8的Function和Optional消除ifelse判断
|
1天前
|
存储 安全 Java
Java HashMap详解
`HashSet` 是 Java 中基于哈希表实现的 `Set` 接口集合,主要用于存储不重复元素,提供快速查找、插入和删除操作。它不允许重复元素,不保证元素顺序,但允许一个 `null` 元素。常用操作包括创建、添加、删除、检查元素及清空集合。由于其哈希表结构,`HashSet` 在插入、删除和查找操作上具有常数时间复杂度 O(1),性能高效。适用于需要快速访问和操作的场景,但需注意其无序性和线程安全问题。
|
7天前
|
域名解析 分布式计算 网络协议
java遍历hdfs路径信息,报错EOFException
java遍历hdfs路径信息,报错EOFException
21 3
|
2月前
|
存储 Java 数据处理
如何使用 Java 迭代 HashMap 中的 ArrayList
【8月更文挑战第23天】
43 2
|
2月前
|
安全 Java
【Java集合类面试十五】、说一说HashMap和HashTable的区别
HashMap和Hashtable的主要区别在于Hashtable是线程安全的,不允许null键和值,而HashMap是非线程安全的,允许null键和值。
|
2月前
|
安全 Java
【Java集合类面试十三】、HashMap如何实现线程安全?
实现HashMap线程安全的方法包括使用Hashtable类、ConcurrentHashMap,或通过Collections工具类将HashMap包装成线程安全的Map。
|
2月前
|
安全 Java
【Java集合类面试十六】、HashMap与ConcurrentHashMap有什么区别?
HashMap是非线程安全的,而ConcurrentHashMap通过减少锁粒度来提高并发性能,检索操作无需锁,从而提供更好的线程安全性和性能。
|
2月前
|
Java
【Java集合类面试十四】、HashMap是如何解决哈希冲突的?
HashMap解决哈希冲突的方法是通过链表和红黑树:当链表长度超过一定阈值时,转换为红黑树以提高性能;当链表长度缩小到另一个阈值时,再转换回链表。
|
2月前
|
存储 开发者 C#
WPF与邮件发送:教你如何在Windows Presentation Foundation应用中无缝集成电子邮件功能——从界面设计到代码实现,全面解析邮件发送的每一个细节密武器!
【8月更文挑战第31天】本文探讨了如何在Windows Presentation Foundation(WPF)应用中集成电子邮件发送功能,详细介绍了从创建WPF项目到设计用户界面的全过程,并通过具体示例代码展示了如何使用`System.Net.Mail`命名空间中的`SmtpClient`和`MailMessage`类来实现邮件发送逻辑。文章还强调了安全性和错误处理的重要性,提供了实用的异常捕获代码片段,旨在帮助WPF开发者更好地掌握邮件发送技术,提升应用程序的功能性与用户体验。
36 0
|
2月前
|
存储 Java 开发者
揭秘!HashMap底层结构大起底:从数组到链表,再到红黑树,Java性能优化的秘密武器!
【8月更文挑战第24天】HashMap是Java集合框架中的核心组件,以其高效的键值对存储和快速访问能力广受开发者欢迎。在JDK 1.8及以后版本中,HashMap采用了数组+链表+红黑树的混合结构,实现了高性能的同时解决了哈希冲突问题。数组作为基石确保了快速定位;链表则用于处理哈希冲突;而当链表长度达到一定阈值时,通过转换为红黑树进一步提升性能。此外,HashMap还具备动态扩容机制,当负载因子超过预设值时自动扩大容量并重新哈希,确保整体性能。通过对HashMap底层结构的深入了解,我们可以更好地利用其优势解决实际开发中的问题。
64 0
下一篇
无影云桌面