Java hashmap values to array

Java – Convert a Map to Array, List or Set

This Java tutorial will teach how to convert Map keys and values to the array, List or Set. Java maps are a collection of key-value pairs. The Map keys are always unique but can have duplicate values.

For demo purposes, let us create a Map with String keys and Integer values.

The Map.values() returns a collection view of the values contained in this map. Use Collection.toArray() to get the array from collection elements. This method takes the runtime type of the returned array.

Collection values = map.values(); Integer valArray[] = values.toArray(new Integer[0]);

Similarly, we can collect the Map keys into an array. Map.keyset() returns the Set of all the keys in a Map. Using Set.toArray() we can convert it to an array of Strings.

String keyArray[] = map.keySet().toArray(new String[0]);

We can collect the Map values into a List using the ArrayList constructor which takes a collection of values as its parameter.

List valList = new ArrayList<>(map.values());

We can use Java Streams to achieve the same result.

List listOfValues = map.values().stream().collect(Collectors.toCollection(ArrayList::new)); 

Likewise, we can convert Map keys to List using plain Java and Streams.

List keyList = new ArrayList<>(map.keySet()); //ArrayList Constructor List listOfKeys = map.keySet().stream().collect(Collectors.toCollection(ArrayList::new)); //Streams

We can use the HashSet constructor or Streams to convert Map values to a Set.

Set valSet = new HashSet<>(map.values()); //HashSet Constructor Set setOfValues = map.values().stream().collect(Collectors.toCollection(HashSet::new)); //using Streams

The Map.keySet() returns a Set view of all the keys in the Map.

This tutorial taught us how to convert Java Map keys and values into an Array, List or Set with simple examples. We learned to use the ArrayList and HashSet constructors as well as Stream APIs.

Источник

convert a hashmap to an array [duplicate]

I want to convert this to an array, say Temp[], containing as first value the key from the hashmap and as second the String[]-array from the map, also as array. Is this possible? How?

Your question isn’t clear — are you talking about an array of a new class, where each instance contains the key and value from the map?

4 Answers 4

hashMap.keySet().toArray(); // returns an array of keys hashMap.values().toArray(); // returns an array of values 

code is like this by now: ` HashMap map = new HashMap(); map.put(«key1», new String[]); map.put(«key2», new String[]); Object[][] twoDarray = new String[map.size()][]; Object[] keys = map.keySet().toArray(); Object[] values = map.values().toArray(); System.out.println(values[1]); System.out.println(values[2]);` output is broken. gives back [Ljava.lang.String;@1f33675 Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: 2 at test.main(test.java:17)

@tetsuya You are trying to access the third element backed in the Values() HashSet, which according to your input doesnt exist, hence u get that RuntimeException

Читайте также:  Python поиск измененных файлов

@tetsuya Index in arrays are starting at 0. So you can access only values[0] and values[1] if you have 2 entries in your map.

Hm. Your question is really strange, but here is what you asked:

HashMap map = new HashMap(); String[] keys = map.keySet().toArray(); Object[] result = new ObjectJava hashmap values to array; //the array that should hold all the values as requested for(int i = 0; i < keys.length; i++) < result[i] = keys[i]; //put the next key into the array result[i+1] = map.get(keys[i]); //put the next String[] in the array, according to the key. >

But man, for what should you ever need something like this? Whatever you want to do, The chance is over 99% that you don’t need to write something like this.

I guess, you just need to write a method, that does what you want.

I’m not sure if this is what you needed but here is your code that I modified:

 Map map = new HashMap(); map.put("key1", new String[]); map.put("key2", new String[]); Object[] keys = map.keySet().toArray(); Object[] values = map.values().toArray(); System.out.println("key = " + keys[0] + ", value #1 = " + ((Object[])values[0])[0]); System.out.println("key = " + keys[1] + ", value #1 = " + ((Object[])values[1])[0] + ", value #2 key2" instead of "key1". That is because HashMap doesn't keep the keys in the same order you add them. To change that you must choose another Map implementation (for example TreeMap if you want to have alphabetical order).

How this works? Java allows you to cast arrays to Object. toArray() method returns Object[] - an array of Objects, but those objects are also arrays (of String - as you defined in your map)! If you print just value[0] it would be like printing mySampleArray where mySampleArray is:

Object[] mySampleArray = new Object[5]; 

So you call it on the whole array not an element. This is why you get [Ljava.lang.String;@7c6768 etc. (which is className@HashCode - thats what default toString() method does).

In order to get to your element you have to go deeper.

This means: Take values[0] (we know it holds an array), cast it to array and take first element.

I hope this helps, please let me know if you need any additional info.

Источник

Java Hashmap values to Array

I have the following code which adds some arrays to a hashmap but then I want access those arrays to do some work on them later. I've gotten this far but can't figure the rest out to make it work.

import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; public static void main(String[] args) < String[][] layer1 = < , >; String[][] layer2 = < , >; HashMap hashMap = new HashMap(); hashMap.put("layer1", layer1); hashMap.put("layer2", layer2); Iterator> iterator = hashMap.entrySet().iterator(); while(iterator.hasNext()) < hashMap.values().toArray(); for (. ) < // lets print array here for example >> > 

4 Answers 4

Smells like homework, but a few suggestions -

You're iterating twice. You either - iterate through the map, either the keys, values or entries. Each item is an iterator return value, e.g.

  • hashmap.values.toArray gives you all of the contents, which is the same thing your iterator is doing.
  • if you're only iterating through the contents, then you're not really using a map, as you're never making use of the fact that your values are available by key.

. just mixing too many languages to learn atm

Can I suggest that you need to stop and take the time to learn Java properly. Your code looks like you are trying to write "perlish" . associative arrays and arrays instead of proper types. The end result is Java code that is slow and fragile compared with code that is designed and written using the Java mindset.

It might seem like you are being productive, but what you are producing is likely to be problematic going forward.

Your while loop should look like -

Your code is bad formed here:

You try to iterate using the Iterator "iterator" but next you call to

To get the next item of the loop you need to use iterator.next(); to fetch it. Also is good to change the "Object" by String[][] or to List or List> .

import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Map.Entry; public static void main(String[] args) < String[][] layer1 = < , >; Map map= new HashMap(); map.put("layer1", layer1); Iterator> iterator = map.entrySet().iterator(); while(iterator.hasNext()) < Entryentry = iterator.next(); System.out.println("Key:" + entry.getKey()); String[][] value = entry.getValue(); for(int x=0;x > > > 

Also you can use "for each" loop to simplify the code insted using the "while":

for (Entry entry : map.entrySet()) < System.out.println("Key:" + entry.getKey()); String[][] value = entry.getValue(); for(int x=0;x> > 

Or if you only need the values:

for (Entry entry : map.values()) < String[][] value = entry.getValue(); for(int x=0;x> > 

Источник

How does one convert a HashMap to a List in Java?

This probably should not be a question -- or you should turn it into a proper question and accept the first reasonable answer that comes along? It makes it harder to find a real question that needs answering.

If requirement to return a List is not a must, I think converting Collection or Set to ArrayList does not make much sense to me. Just return the collection or the Set that you get from HashMap

8 Answers 8

HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); List list = new ArrayList(map.values()); for (String s : list)

Basically, the .values() method of the HashMap class returns a Collection of the values. You can also use .keys() for that matter. The ArrayList() class accepts a Collection as one of its constructors. Hence, you create a new ArrayList from a Collection of the HashMap values. I have no idea what the performance is like, but for me the simplicity is worth it!

HashMap map; // Assigned or populated somehow. 
List values = new ArrayList(map.values()); 
List keys = new ArrayList(map.keySet()); 

Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.

+1 for noting proper ordering should use LinkedHashMap <=>List . Also, it's probably good practice for the unordered conversions to use HashMap <=>Set to indicate that it's unordered.

Basically you should not mess the question with answer, because it is confusing.

Then you could specify what convert mean and pick one of this solution

List keyList = Collections.list(Collections.enumeration(map.keySet())); List valueList = Collections.list(Collections.enumeration(map.values())); 

@Joachim, that is the correct method name that im thankful for. But if you want to convert the Set into list this is the way.

qVash: why? you can simply use new ArrayList(map.keySet()) which is a more direct route and avoid creating an Enumeration . And I'm almost certain that it will perform better, because the ArrayList will be created with the correct size from the very beginning.

@Mark: the end effect is the same as what you posted: You'll have a new ArrayList referencing the same object that are also referenced by the Map .

Collection Interface has 3 views

Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct

My addition: How to convert "key-value pair" (aka entrySet)into list.

 Map m=new HashMap(); m.put(3, "dev2"); m.put(4, "dev3"); List entryList = new ArrayList(m.entrySet()); for (Entry s : entryList)

ArrayList has this constructor.

Solution using Java 8 and Stream Api:

private static List createListFromMapEntries (Map map)
 public static void main (String[] args) < Mapmap = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); map.put(3, "three"); List result = createListFromMapEntries(map); result.forEach(System.out :: println); > 

If you only want it to iterate over your HashMap, no need for a list:

HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); for (String s : map.values())

Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:

HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); for (String s : map.values().toArray(new String[]<>))

Источник

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