From eab67c04b5bb0357b587eb1c34033253203ff269 Mon Sep 17 00:00:00 2001 From: akeshri Date: Sat, 29 Aug 2020 21:02:52 +0530 Subject: [PATCH] changes --- .../com/baeldung/article/HashMapExample.java | 36 ++++++++++++++++++ .../article/LinkedHashMapExample.java | 37 +++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 MapFirstKeyExample/src/com/baeldung/article/HashMapExample.java create mode 100644 MapFirstKeyExample/src/com/baeldung/article/LinkedHashMapExample.java diff --git a/MapFirstKeyExample/src/com/baeldung/article/HashMapExample.java b/MapFirstKeyExample/src/com/baeldung/article/HashMapExample.java new file mode 100644 index 0000000000..3292d995ab --- /dev/null +++ b/MapFirstKeyExample/src/com/baeldung/article/HashMapExample.java @@ -0,0 +1,36 @@ +package com.baeldung.article; + +import java.util.AbstractMap; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * @author AshwiniKeshri + * + */ +public class HashMapExample { + public static void main(String[] args) { + + Map hashmap = new HashMap<>(); + hashmap.put(5, "A"); + hashmap.put(1, "B"); + hashmap.put(2, "C"); + // hashmap.put(0, "D"); + + System.out.println(hashmap); + + Set> entrySet = hashmap.entrySet(); + + Iterator> iterator = entrySet.iterator(); + + if (iterator.hasNext()) + System.out.println("Using Iteraor: " + iterator.next()); + + System.out.println("Using Stream: " + entrySet.stream() + .findFirst() + .orElse(new AbstractMap.SimpleEntry(-1, "DEFAULT"))); + + } +} diff --git a/MapFirstKeyExample/src/com/baeldung/article/LinkedHashMapExample.java b/MapFirstKeyExample/src/com/baeldung/article/LinkedHashMapExample.java new file mode 100644 index 0000000000..249b9a0585 --- /dev/null +++ b/MapFirstKeyExample/src/com/baeldung/article/LinkedHashMapExample.java @@ -0,0 +1,37 @@ +package com.baeldung.article; + +import java.util.AbstractMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * @author AshwiniKeshri + * + */ +public class LinkedHashMapExample { + + public static void main(String[] args) { + + LinkedHashMap linkedHashMap = new LinkedHashMap<>(); + linkedHashMap.put(5, "A"); + linkedHashMap.put(1, "B"); + linkedHashMap.put(2, "C"); + // linkedHashMap.put(0, "D"); + + System.out.println(linkedHashMap); + + Set> entrySet = linkedHashMap.entrySet(); + + Iterator> iterator = entrySet.iterator(); + + if (iterator.hasNext()) + System.out.println("Using Iterator: " + iterator.next()); + + System.out.println("Using Stream: " + entrySet.stream() + .findFirst() + .orElse(new AbstractMap.SimpleEntry(0, "DEFAULT"))); + } + +}