Get all elements hashmap java

Java HashMap key value storage and retrieval

I want to retrieve all Keys and Values from the HashMap as a Java Collection or utility set (for example LinkedList ). I know I can get the value if I know the key, like this:

6 Answers 6

I use these three ways to iterate a map. All methods ( keySet , values , entrySet ) return a collection.

// Given the following map Map myMap; // Iterate all keys for (KeyClass key : myMap.keySet()) System.out.println(key); // Iterate all values for (ValueClass value : myMap.values()) System.out.println(value); // Iterate all key/value pairs for (Entry entry : myMap.entrySet()) System.out.println(entry.getKey() + " - " + entry.getValue()); 

Since Java 8 i often use Stream s with lambda expressions.

 // Iterate all keys myMap.keySet().stream().forEach(key -> System.out.println(key)); // Iterate all values myMap.values().parallelStream().forEach(value -> System.out.println(value)); // Iterate all key/value pairs myMap.entrySet().stream().forEach(entry -> System.out.println(entry.getKey() + " - " + entry.getValue())); 

Java Hashmap key value example:

public void processHashMap() < //add keys->value pairs to a hashmap: HashMap hm = new HashMap(); hm.put(1, "godric gryfindor"); hm.put(2, "helga hufflepuff"); hm.put(3, "rowena ravenclaw"); hm.put(4, "salazaar slytherin"); //Then get data back out of it: LinkedList ll = new LinkedList(); Iterator itr = hm.keySet().iterator(); while(itr.hasNext()) < String key = itr.next(); ll.add(key); >System.out.print(ll); //The key list will be printed. > 

map.keySet() would give you all the keys

//import statements import java.util.HashMap; import java.util.Iterator; import java.util.TreeMap; // hashmap test class public class HashMapTest < public static void main(String args[]) < HashMaphashMap = new HashMap(); hashMap.put(91, "India"); hashMap.put(34, "Spain"); hashMap.put(63, "Philippines"); hashMap.put(41, "Switzerland"); // sorting elements System.out.println("Unsorted HashMap: " + hashMap); TreeMap sortedHashMap = new TreeMap(hashMap); System.out.println("Sorted HashMap: " + sortedHashMap); // hashmap empty check boolean isHashMapEmpty = hashMap.isEmpty(); System.out.println("HashMap Empty: " + isHashMapEmpty); // hashmap size System.out.println("HashMap Size: " + hashMap.size()); // hashmap iteration and printing Iterator keyIterator = hashMap.keySet().iterator(); while(keyIterator.hasNext()) < Integer key = keyIterator.next(); System.out.println("Code=" + key + " Country=" + hashMap.get(key)); >// searching element by key and value System.out.println("Does HashMap contains 91 as key: " + hashMap.containsKey(91)); System.out.println("Does HashMap contains India as value: " + hashMap.containsValue("India")); // deleting element by key Integer key = 91; Object value = hashMap.remove(key); System.out.println("Following item is removed from HashMap: " + value); > > 

You can use keySet() to retrieve the keys. You should also consider adding typing in your Map, e.g :

Map hm = new HashMap(); hm.put(1,"godric gryfindor"); hm.put(2,"helga hufflepuff"); hm.put(3,"rowena ravenclaw"); hm.put(4,"salazaar slytherin"); Set keys = hm.keySet(); 
void hashMapExample() < HashMaphMap = new HashMap(); hMap.put("key1", "val1"); hMap.put("key2", "val2"); hMap.put("key3", "val3"); hMap.put("key4", "val4"); hMap.put("key5", "val5"); if(hMap != null && !hMap.isEmpty()) < for(String key : hMap.keySet())< System.out.println(key+":"+hMap.get(key)); >> > 

Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.

Читайте также:  Длина байтовой строки python

Источник

Map implementation classes:

2. Get all keys using keySet() method and retrieve corresponding values

GetAllKeysOfHashMap.java

package in.bench.resources.java.map; import java.util.HashMap; import java.util.Set; public class GetAllKeysOfHashMap < public static void main(String[] args) < // creating HashMap object of type HashMap hm = new HashMap(); // adding key-value pairs to HashMap object hm.put("Google", "Sundar Pichai"); hm.put("Facebook", "Mark Zuckerberg"); hm.put("LinkedIn", "Reid Hoffman"); hm.put("Apple", "Steve Jobs"); hm.put("Microsoft", "Bill Gates"); System.out.println("all Key-Value pairs:\n\n" + hm + "\n\n"); System.out.println("List of all keys using keySet(): \n"); // Iterating keys using keySet() Set companies = hm.keySet(); for(String company : companies) < System.out.println("Key : " + company + "\t\t" + "Value : " + hm.get(company)); >> >
all Key-Value pairs: List of all keys using keySet(): Key : LinkedIn Value : Reid Hoffman Key : Facebook Value : Mark Zuckerberg Key : Google Value : Sundar Pichai Key : Apple Value : Steve Jobs Key : Microsoft Value : Bill Gates
  • How to get all keys of a HashMap
  • How to get all values of a HashMap
  • How to get all Entries or Key-Value pairs of HashMap
  • How to get size or length of HashMap
  • How to check whether a particular key is present in HashMap
  • How to check whether a particular value is present in HashMap
  • How to check whether HashMap is empty or not ?
  • Adding one HashMap to another HashMap using putAll method
  • How to delete an entry of HashMap
  • How to delete all entries of HashMap
  • How to remove an entry from HashMap by comparing values in Java 8
  • How to remove an entry from HashMap by comparing keys in Java 8
  • Various ways to iterate through HashMap
  • To reverse order the LinkedHashMap contents
  • Map: How ConcurrentModificationException can be handled in Java
Читайте также:  Kotlin get field by name

References:

  • https://docs.oracle.com/javase/tutorial/collections/intro/
  • https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
  • https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
  • https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
  • https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
  • https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
  • https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
  • https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
  • https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
  • https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
  • https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
  • https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
  • http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html
  • https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html
  • https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
  • https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html

Happy Coding !!
Happy Learning !!

Источник

Get array elements from HashMap in Java

that means the array contains a class or interface. One solution would be looping on the array and print each part (or using Arrays.toString method), but I highly recommend you wrapping this to your own class and override the toString method.

Yes, this exactly worked. I tried to adopt your answer like this : ` System.out.println(pair.getKey() + » = » + Arrays.toString((Object[]) pair.getValue()));` It did give me contents in readable format.

@mk08 Thought I really encourage you to have a custom class containing all of the fields you want. It’s more encapsulated and a better practice.

This object is actually getting created on runtime when Jsoup parser connects to URL and scans the entire DOM . This may be basic question as I have not used Java at this extent, but for this scenario also would you suggest to have separate class?

@mk08 Sure, you can pass the result of Jsoup to the constructor of the class where you actually create the new class.

The following code might help. Its always better to create a bean class consisting of the necessary information to be stored in an array of objects.

package stack.overflow; import java.util.HashMap; import java.util.Map; public class RetrieveMap < public static void main(String[] args) < Person p = new Person(); p.setName("John"); p.setEmpNo("1223"); p.setAge("34"); Person p1 = new Person(); p1.setName("Paul"); p1.setEmpNo("1224"); p1.setAge("35"); Person[] arr = new Person[2]; arr[0] = p ; arr[1] = p1; HashMapmap = new HashMap(); map.put("a1", arr); for(Map.Entry entry : map.entrySet()) < System.out.println("Key:" +entry.getKey()); System.out.println("Value:" +entry.getValue()); for(int i=0;i> > > package stack.overflow; public class Person < String name; String age; String empNo; public String getName() < return name; >public void setName(String name) < this.name = name; >public String getAge() < return age; >public void setAge(String age) < this.age = age; >public String getEmpNo() < return empNo; >public void setEmpNo(String empNo) < this.empNo = empNo; >> 

The short answer is your code is behaving exactly correctly; when you call .toString() on an Object[] (which happens implicitly with System.out.println() ) you get that odd [@ string. To print the contents of an array, use Arrays.toString() .

There are a number of things we can clean up with this code, though.

  • Avoid mixing generics and arrays (Effective Java Item 25); arrays lack the type safety generics provide, and there’s rarely a good reason to use them in modern generic code. A better type signature would be HashMap> . This is effectively identical, but in practice much easier to work with.
  • Don’t use arrays to store different types. You appear to be storing a «Test» string, a identifier string, the element’s text, and the text’s length as fields in an array. This is what objects are for. Define an object with those four fields, and pass them into the constructor. Even better, since everything but i is computable from the element, just pass the element into the constructor and compute the information you need (HTML string, length, etc.) in the constructor or even in the class’ getters.
  • Don’t use raw types (Effective Java Item 23) for Iterator s and Map.Entry s. Your IDE can warn you when you use raw types so you avoid this common programming error. In your code you should use Iterator> and Entry
  • Don’t use Iterator to loop over a Map ‘s elements, use a for-each loop:

Here’s a cleaned-up version of your code, assuming a Container object exists that takes an Element and extracts the data you need.

doc = Jsoup.connect(url).get(); for (org.jsoup.nodes.Element element : doc.getAllElements()) < for (Attribute attribute : element.attributes()) < Container c = new Container(i++, attribute); data.put(c.getKey(), c); >> 

HashMap map = HTMLDocument.createHTMLMap(«URL of website»); for (Entry e : map.entrySet())

Источник

Get all elements hashmap java

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the «capacity» of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that using many keys with the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable , this class may use comparison order among keys to help break ties. Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be «wrapped» using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(. ));

The iterators returned by all of this class’s «collection view methods» are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.

Nested Class Summary

Nested classes/interfaces inherited from class java.util.AbstractMap

Nested classes/interfaces inherited from interface java.util.Map

Constructor Summary

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).

Источник

Оцените статью