This question already has answers here:
How do I convert a Map to List in Java?
(13 answers)
Closed 8 years ago.
I have this code :
ArrayList<Integer> users = new ArrayList<Integer>();
Map <String,Object> hashMap = new HashMap <String,Object> ();
hashMap.put("users",user);
// now I want to get users as array list
hashMap.get("users")[i];//error
How to users as array ? thank you
List<Integer> users = new ArrayList<Integer>();
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("users",user);
....
....
....
List<Integer> users = (List<Integer>)hashMap.get("users"); //assuming this is another method and 'users' is not defined here yet
Integer[] usersArray = users.toArray(new Integer[users.size()]);
System.out.println("" + usersArray[i]);
Please note that this is an atrocity and you shouldn't be storing that List as an Object, you are pretty much circumventing what Generics are for.
This code will work if you want to access it as an ArrayList:
List<Integer> users = new ArrayList<Integer>();
Map<String, List<Integer>> hashMap = new HashMap<String, List<Integer>> ();
hashMap.put("users",users);
hashMap.get("users");
Your code won't work since you were storing it as an Object. So you would need a cast. And even then you use [] for arrays, not ArrayLists
If you want to use it as an array you can change the last line to:
hashMap.get("users").toArray()
And then you can use [1], or just do .get(1) on the initial code.
Alternatively, if you want to use hashMap as a property bag as someone validly mentioned you would need to do a cast:
((ArrayList<Integer>) hashMap.get("users"))
Then you can use users as an ArrayList as you are getting an Object by default from the HashMap.
You can try something like following
List<Users> usersList = new ArrayList<>();
Map<String,List<Users>> hashMap = new HashMap <> ();
hashMap.put("user",usersList);
Now
hashMap.get("user")
Will return a List of Users, Now you can use
hashMap.get("user").get(0); // to get 0th index user
Because it is ArrayList and not array,You can get it like this-
public static void main(String args[]) throws Exception
{
ArrayList<Integer> users = new ArrayList<Integer>();
users.add(5);
users.add(10);
Map <String,Object> hashMap = new HashMap <String,Object> ();
hashMap.put("users",users);
ArrayList<Integer> no = ((ArrayList<Integer>) hashMap.get("users"));
for (Integer integer : no) {
System.out.println(integer);
}
}
output-
5
10
Now to convert ArrayList to Array -
Integer[] arr = no.toArray(new Integer[no.size()]);
Related
I'm new to Java and I'm struggling to figure out something trivial.
I have a HashMap with keys of type String and values of type ArrayList <String>, and it returns something like this:
dict = {Color=[Blue, Purple]}
I'm struggling to figure out how I can grab a specific element from the array in the value of dict. Like if I got dict.value[0], it would return the string 'Blue'.
I've tried doing:
Object values = dict.values().toArray[0];
and I assumed that since I changed it to an array, I could do something like values.get(0) to get the first element, but that doesn't work because values is type Object. Any ideas on how to resolve this?
if your HashMap is like:
Map<String, List<String>> myColorsMap = new HashMap<>();
And after populating the map is like:
{Red=[firstRed, secondRed, thirdRed], Blue=[firstBlue, secondBlue, thirdBlue]}
then you can retrieve Blue's key value (a List) like:
String blueFirstElement = myColorsMap.get("Blue").get(0); // --> will give first element of List<String> stored against Blue key.
To get collection of all keys in your map (or "dictionary"):
myColorsMap.keySet();
will give:
[Red, Blue]
When you do:
Object values = dict.values().toArray[0];
First, this is wrong. What you were trying to do is this:
Object values = dict.values().toArray();
Which returns Object[] and it is ambiguous. No need to do that. Java's Map interface and HashMap implementation have a lot of utility methods for you to iterate and retrieve your values.
First, use .get() on map to get the ArrayList using key
List<String> colors = dict.get("Color");
Then use .get() on list to get the element using index
String color = colors.get(0);
You can do this in one line this way
String color = dict.get("Color").get(0);
You are trying with dict.values().toArray[0] which is wrong syntax thats the problem. dict.values() will return Collection<List<String>>, you can get List of values this way
List<List<String>> listOfValues = new ArrayList<>(colorsMap.values());
Then you can access each value by index using .get()
List<String> colors = listOfValues.get(0);
Note : HashMap don't store any order.
Cast to type of java.util.List, and then you can get value through index.
#SuppressWarnings("unchecked")
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>(2);
map.put("color", Arrays.asList("blue", "yellow", "green", "white"));
map.put("size", Arrays.asList("small", "medium", "large"));
List<String> o = (List<String>) map.values().toArray()[0];
System.out.println(o.get(0)); //output is 'blue'
List<String> s = (List<String>) map.values().toArray()[1];
System.out.println(s.get(1)); //output is 'medium'
}
This question already has answers here:
How to get the first element of the List or Set? [duplicate]
(9 answers)
Closed 3 years ago.
How do I get the string value from below snippet:
List<Map<String, Object>> list1= (List<Map<String, Object>>) mymap.get("getProduct");
Map<String, Object> myList= list1.get(0);
List<String> myproduct= (List<String>) myList.get("productName");
System.out.println("value " +myproduct.toString());
When I try to print this I'm always getting as an object instead of plain string.
My Output:
[Apple]
Expected output:
Apple
I'm very new to Java, any help would be really appreciated.
Because myproduct is List with string values, for example below is list with fruit names
List<String> fruits = new ArrayList<>();
list.add("apple");
list.add("mango");
System.out.println(fruits); //[apple,mango]
If you want each value from list you can simply iterate using for each loop
for(String str : myproduct) {
System.out.println(str);
}
If you just need first element you can get by index, but might end up with index out of bound exception if list is empty
String ele = myproduct.get(0);
or by using java-8 stream
String ele = myproduct.stream().findFirst().orElse(null);
I have a small question about converting 2d arraylist to hashmap in java. I have a dataset looks like this after reading as 2d arraylist:
0 1
0 2
1 2
1 3
Which first column stands for id and second column stands for the item. I would like to create frequent itemset using hashmap in java, the output should look like
1 0
2 0 1
3 1
I use these codes but I have some trouble on them:
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(Integer elem : data){
map.put(elem[1], elem[0]);
}
Where data is my 2d arraylist.
The error message said that
incompatible types: ArrayList<Integer> cannot be converted to Integer
for(Integer elem : data){
^
Any help will be appreciated!
You go like this:
List<List<Integer>> inputData = ...
Map<Integer, List<Integer>> dataAsMap = new HashMap<>();
for(List<Integer> row : data){
Integer id = row.get(0);
Integer item = row.get(1);
List<Integer> rowInMap = dataAsMap.get(item);
if (rowInMap == null) {
rowInMap = new ArrayList<>();
dataAsMap.put(item, rowInMap);
}
rowInMap.add(id);
}
Some notes:
You should only be using the interface types List, Map ... as types (you only specify the specific impl type such as HashMap when creating new objects!)
Your problem is: when using for-each on List of Lists (as you did) ... you don't get the individual "cells" Instead, you get Lists [ iterating lists of lists ... results in one list per iteration!]
So, what is left then is to fetch the elements of that inner List, and push them into the Map. The one other part to pay attention to: you want to create a Map of List objects. And those List objects need to be created as well!
( I didn't run the above through a compiler, so beware of typos, but in general it should be telling you what you need to know. If you don't get what the code is doing, I suggest adding println statements or running it in a debugger)
Here is one easy way of doing it:
Take Map<Integer, List<Integer>>
Iterate your Arraylist.
See if key is already present in the map. Retrieve the list and add the value to the list if key is present or else create a new list with the value.
Program:
class FooBar {
public static void main (String[] args) throws Exception {
int[][] data = {{0,1}, {0,2}, {1,2}, {1,3}};
Map<Integer, List<Integer>> myMap = new HashMap<>();
for(int i = 0; i < 4; i++) {
List<Integer> values = myMap.containsKey(data[i][0]) ?
myMap.get(data[i][0]) : new ArrayList<>();
values.add(data[i][1]);
myMap.put(data[i][0], values);
}
System.out.println(myMap);
}
}
Output:
{0=[1, 2], 1=[2, 3]}
This is just to illustrate the basic method. You can obviously modify it to suit your needs. For example, you can have String instead of List<Integer> and choose to append the values to the String instead of adding it to the List.
EDIT:
Here is a sample program with List<List<Integer>> as input. Here I'm assuming the name of this list as input.
Program:
class FooBar {
public static void main (String[] args) throws Exception {
/* Input Data */
List<List<Integer>> input = new ArrayList<>();
input.add(new ArrayList<Integer>(){{add(0); add(1);}});
input.add(new ArrayList<Integer>(){{add(0); add(2);}});
input.add(new ArrayList<Integer>(){{add(1); add(2);}});
input.add(new ArrayList<Integer>(){{add(1); add(3);}});
Map<Integer, List<Integer>> myMap = new HashMap<>();
for(int i = 0; i < input.size(); i++) {
List<Integer> values = myMap.containsKey(input.get(i).get(0)) ?
myMap.get(input.get(i).get(0)) : new ArrayList<>();
values.add(input.get(i).get(1));
myMap.put(input.get(i).get(0), values);
}
System.out.println(myMap);
}
}
Output:
{0=[1, 2], 1=[2, 3]}
This question already has answers here:
HashMap with multiple values under the same key
(21 answers)
Closed 6 years ago.
Actually I have to merge duplicate key's value into existing key instead of replace, for that which map I have to use, I tried hashmap but it is replacing the values. Thanks...
Store them in a map, with each line of input append that to any existing value.
eg somthing like (sudo code)
Map map= new HashMap();
for (key,value) in inputdata
map.put(key, join(map.get(key),value));
Java8 Maps have a merge method that let's you modify the value associated to a given key if needed.
Suppose each value is a list (afterall if you want multiple values for a given key)...
List<Integer> l1 = new ArrayList<Integer>(); l1.add(1);
List<Integer> l2 = new ArrayList<Integer>(); l2.add(2);
List<Integer> l3 = new ArrayList<Integer>(); l3.add(3);
List<Integer> l4 = new ArrayList<Integer>(); l4.add(4);
BiFunction<Collection<Integer>,Collection<Integer>,Collection<Integer>> mergeFunc = (old,new)-> { old.addAll(new); return old; };
myMap.merge("one",l1,mergeFunc);
myMap.merge("two",l2,mergeFunc);
myMap.merge("three",l3,mergeFunc});
myMap.merge("one",l4,mergeFunc);
I am new to Java and I literally have no idea how to do this.
I have this Java array:
String luni[];
luni = new String[] {"A","B","C"};
and I want each value A,B,C from the array to become a HashSet variable, like this:
Set<String> luni[0] = new HashSet<>(500);
Set<String> luni[1] = new HashSet<>(500);
Set<String> luni[2] = new HashSet<>(500);
Eventually having A,B,C as HashSet to which I can later use luni[0].add("string");
I hope you get the idea. How can I do this, it seems it won't work as I wrote it?
You can use a HashMap in your case it will have a String keys and HashSet values.
HashMap<String, HashSet<Whatever>> map
= new HashMap<String, HashSet<Whatever>>();
Original answer was:
If you just need to access each HashSet in the array by index,
luni[0].add("string"), then you simply have to define luni as an
array of Sets:
But in fact, you'll need to use an ArrayList of Sets (or use an array of raw Set, but that's not as good), and you'll still be able to use it with an index:
Note that this is only good if you don't have any actual use for the "A", "B", "C" and you just wanted to access the hashsets by index.
List<Set<String>> luni = new ArrayList<Set<String>>();
luni.add( new HashSet<String>(500) );
luni.add( new HashSet<String>(500) );
luni.add( new HashSet<String>(500) );
luni.get(0).add("String");
Either use:
Map<String, Set<String>> luni = new HashMap<>();
luni.put("A", new HashSet<String>(500));
luni.put("B", new HashSet<String>(500));
luni.put("C", new HashSet<String>(500));
// To add a value to B:
luni.get("B").add("some string");
or:
List<Set<String>> luni = new ArrayList<>(3);
luni.add(new HashSet<String>(500));
luni.add(new HashSet<String>(500));
luni.add(new HashSet<String>(500));
// To add a value to 'B' (index 1):
luni.get(1).add("some string");
I suggest using the first one. The second one uses index instead of A, B and C like you want.