Get array key java

java Get hashmap keys as integer array

Yes, integers are perfectly fine for being used as keys in a Map. It’s just that you will be putting an Integer instead of the primitive int in the Map but I don’t think that should be a problem for you. Also, auto-boxing will help you cut down the conversion from int to Integer call.

4 Answers 4

There is no direct way of converting a list of String s to a list of Integer s:

    Either you need to redefine your valueHashMap like this:

public HashMap valueHashMap = new HashMap(); . ArrayList intKeys = new ArrayList(valueHashMap.keySet()); 
ArrayList intKeys = new ArraList(); for (String stringKey : valueHashMap.keySet()) intKeys.add(Integer.parseInt(stringKey); 
public HashMap valueHashMap = new HashMap(); 

You can’t cast a List of one type to a List of another type, so you have to iterate through the keys and parse each one.

for(String k : valueHashMap.keySet())

@Joachim Sauer: That’s because my answer covered the general case (where you can sometimes cast) and my code was for this specific instance of the problem. Fixed it anyway to avoid confusion.

Читайте также:  Php imap move folder

the problem is that many people call any kind of type conversion «casting» and that is wrong and confuses people even further.

You really have type problems. Why do you change the longs into Strings to store them in a map. Why not simply use Long, which needs less memory and is more descriptive. Then why use Integer.toString to transform a long into a String? By casting your long to an int, you risk loosing information by. Here’s how the code should probably look like:

private Map valueHashMap = new Hashmap(); long timeSinceEpoch = System.currentTimeMillis()/1000; valueHashMap.put(timeSinceEpoch, people_obj); List longKeys = new ArrayList(valueHashMap.keySet()); 

You can use org.apache.commons.collections.Transformer class for that as follows.

List intKeys = (List)CollectionUtils.collect(valueHashMap.keySet(), new Transformer() < @Override public Object transform(Object key) < return Integer.valueOf(key); >>, new ArrayList()); 

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Get Keys From HashMap in Java

Get Keys From HashMap in Java

  1. Use keySet() to Get a Set of Keys From a HashMap in Java
  2. Use keySet() to Get an Array of Keys From a HashMap in Java

This tutorial discusses methods to get the keys from a HashMap in Java.

Use keySet() to Get a Set of Keys From a HashMap in Java

The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap .

In the example below, we will first create a HashMap object, insert some values in it, and then use keySet() to get the keys.

import java.util.*;  public class MyClass   public static void main(String args[])   // Create a HashMap with some values  HashMapString, Integer> map = new HashMapString, Integer>();  map.put("Monday", 5);  map.put("Tuesday", 6);  map.put("Wednesday", 10);   // Invoke keySet() on the HashMap object to get the keys as a set  SetString> keys = map.keySet();  for ( String key : keys )   System.out.println( key );  >  > > 

Use keySet() to Get an Array of Keys From a HashMap in Java

Often we prefer to work with an array instead of a set . The below example illustrates how to use keySet() to get an array of keys from a HashMap in Java.

import java.util.*;  public class MyClass   public static void main(String args[])   // Create a HashMap with some values  HashMapString, Integer> map = new HashMapString, Integer>();  map.put("Monday", 5);  map.put("Tuesday", 6);  map.put("Wednesday", 10);   // Invoke keySet() and use toArray() to get an array of keys  Object[] keys = map.keySet().toArray();  for (int i=0; ikeys.length; i++)   System.out.println( keys[i] );  >  > > 

Related Article — Java HashMap

Источник

Java – Get keys from value HashMap

This article shows a few ways to get keys from value in HashMap.

1. HashMap can contain null for key and value

When we create a method to find keys from value in HashMap , we have to take care of the following concerns:

  1. HashMap can contain null for key and value.
  2. HashMap keys are unique, which means no duplication.
  3. HashMap does not guarantee the insert order.
  4. Single or multiple keys match to a single value.
 Map map = new HashMap<>(); map.put("key1", 1); map.put("key2", 2); map.put("key3", 3); map.put("key4", 3); map.put("key5", null); // null for value map.put(null, 3); // null for key 

2. Get all keys from HashMap – keySet()

The map.keySet() returns a Set , and the HashMap does not guarantee the insert order.

 Map map = new HashMap<>(); map.put("key1", 1); map.put("key2", 2); map.put("key3", 3); map.put("key4", 3); map.put("key5", null); map.put(null, 3); //Set keys = map.keySet(); // print all keys for (String key : map.keySet())
 key1 null key2 key5 key3 key4 

3. Get keys from value in HashMap

To find all the keys that map to a certain value, we can loop the entrySet() and Objects.equals to compare the value and get the key.

Note
The common mistake is use the entry.getValue().equals(value) to compare the value, because if the HashMap contains a null value, the method will throw a popular NullPointerException .

3.1 Find all keys that containing the value of 3 .

 package com.mkyong.basic; import java.util.*; public class FindKeysFromMap < public static void main(String[] args) < Mapmap = new HashMap<>(); map.put("key1", 1); map.put("key2", 2); map.put("key3", 3); map.put("key4", 3); map.put("key5", null); map.put(null, 3); for (String key : getKeys(map, 3)) < System.out.println(key); >> private static Set getKeys(Map map, Integer value) < Setresult = new HashSet<>(); if (map.containsValue(value)) < for (Map.Entryentry : map.entrySet()) < if (Objects.equals(entry.getValue(), value)) < result.add(entry.getKey()); >// we can't compare like this, null will throws exception /*(if (entry.getValue().equals(value)) < result.add(entry.getKey()); >*/ > > return result; > > 

3.2 Find all keys that containing the value of null .

 for (String key : getKeys(map, null))

4. Get keys from value in HashMap (Java 8 Stream)

4.1 Below is an equivalent example in Java 8.

 package com.mkyong.basic; import java.util.*; import java.util.stream.Collectors; public class FindKeysFromMapJava8 < public static void main(String[] args) < Mapmap = new HashMap<>(); map.put("key1", 1); map.put("key2", 2); map.put("key3", 3); map.put("key4", 3); map.put("key5", null); map.put(null, 3); for (String key : getKeysJava8(map, 3)) < System.out.println(key); >> /*private static Set getKeys(Map map, Integer value) < Setresult = new HashSet<>(); if (map.containsValue(value)) < for (Map.Entryentry : map.entrySet()) < if (Objects.equals(entry.getValue(), value)) < result.add(entry.getKey()); >> > return result; >*/ private static Set getKeysJava8( Map map, Integer value) < return map .entrySet() .stream() .filter(entry ->Objects.equals(entry.getValue(), value)) .map(Map.Entry::getKey) .collect(Collectors.toSet()); > > 

4.2 If we want to find only the first key that match the value.

 private static Optional getKeysJava8( Map map, Integer value) < return map .entrySet() .stream() .filter(entry ->Objects.equals(entry.getValue(), value)) .map(Map.Entry::getKey) .findFirst(); > 

4.3 Or if we want a List and Optional .

 private static Optional> getKeysJava8Optional( Map map, Integer value) < Listcollect = map .entrySet() .stream() .filter(entry -> Objects.equals(entry.getValue(), value)) .map(Map.Entry::getKey) .collect(Collectors.toList()); return Optional.of(collect); 

5. HashMap only has one item

5.1 If the HashMap only has one item, we can use map.keySet().toArray() to convert the Set to an Array and [0] to get the first item from the array, which means the first key from the HashMap .

 Map map = new HashMap<>(); map.put("key1", 1); // the first key Object key = map.keySet().toArray()[0]; System.out.println(key); 

5.2 Can we use map.keySet().toArray()[5] to get the sixth key from a HashMap ? The answer is a NO because the result will be a random key, HashMap does not guarantee the insert order.

Do not try this

 Map map = new HashMap<>(); map.put("key1", 1); map.put("key2", 2); map.put("key3", 3); map.put("key4", 3); map.put("key5", null); map.put(null, 3); Object key = map.keySet().toArray()[5]; // we expect the sixth key from a HashMap System.out.println(key); // but the result is a random keys 

Note
The HashMap does not guarantee the insert order, this map.keySet().toArray()[0] only works for HashMap only has one item.

6. References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Источник

How do I get an array of keys from a hashmap that aren’t type Object?

That doesn’t work because it.next() returns Object. My hashmap uses ints for keys. All of my methods accept ints to access the hashmap. How can I actually get an int value when looping through my keys so I can pass it to my other methods?

7 Answers 7

This gives you keys that are Integer (not int, but that cannot be helped). Integer can be automatically unboxed:

for (int key : myHashMap.keySet())

If you want your keys in ascending order, consider using TreeMap instead of HashMap .

First of all try to use Generics while defining your Map / HashMap . Then you don’t need to worry.

Second thing, HashMap doesn’t use primitive type for keys. Which means you are mistaken, and the actual type used as keys is Integer , not int .

A quick fix can be a cast to int , like below

int next = ((Integer) it.next()).intValue(); 

A detailed example, with a new loop syntax (introduced in Java 5).

Map map = new HashMap(); . for(int n : map.keySet())

Actually casting to int does not work. It says cannot cast from object to int. I also couldn’t use Integer.intValue(). I don’t know what type of Object it’s giving me. :\

Note: the quick fix above will only work with Java 5 or above. For lesser you need ((Integer) it.next()).intValue() .

You should use Java generics:

Map myHashMap = new HashMap(); // . for (int key : myHashMap.keySet()) < // . >

HashMaps in Java can only use objects, not primtives.

So it is more likely that your keys are of type Integer, and that when you put stuff in, it gets promoted from int to Integer.

All that being said, this is really old school Java. Your collection should define the key and target type using generics, and there’s also a for-each in Java for(Integer key: myHashMap.keySet())

BTW: be aware that there are no guarantees about the order in which you’ll be iterating.

Your int s are autoboxed into Integer s when you use them as keys in Map s.

As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.

Источник

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