I have a Map , but I want the values of the map to be of type ArrayList
Map m = new HashMap();
since the value of the Key 'A' would itself have multiple values eg. key 'A' has values 10,20,30 please advise how to achieve this, I have created the first step below
LinkedHashMap<String,List<String>> A = new LinkedHashMap<String,List<String>>();
please advise how to add the multiple values in the list next and store it along with the Map in put operation
If I understand the question correctly then this seems to be the right way to me, all you then need to do is either:
List<String> strings = new ArrayList<String>();
strings.add("10");
strings.add("20");
strings.add("30");
A.put(strings);
Or you can:
A.put(Arrays.asList("10", "20", "30"));
Like this -
LinkedHashMap<String,List<String>> A = new LinkedHashMap<String,List<String>>();
List<String> list = new ArrayList<String>();
list.add("10");
list.add("20");
list.add("30");
A.put("a", list);
Like :
List<String> list = new ArrayList<>();
list.add("abc");
list.add("xyz");
// ....
Map<String,List<String>> map = new HashMap<>();
map.put("Key", list);
as I know that, you can use Apache MultiValueMap. It meets your requirement.http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiValueMap.html
Here is a program.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class Test {
public static void main(String[] args) {
LinkedHashMap<String,List<String>> A = new LinkedHashMap<String,List<String>>();
List<String> list = new ArrayList<>();
list.add("1");
A.put("1", list);
//add new values
list = A.get("1");
if(list!=null){
list.add("2");
}else{
list = new ArrayList<String>();
list.add("2");
}
A.put("1", list);
}
}
You can replace List with TreeSet and if the all values are integer then it will be better to use Integer instead of String
Here in example taken Integer type while just replace it with String it will work fine as well.
public static void main(String[] args) {
LinkedHashMap<String, TreeSet<Integer>> lhm = new LinkedHashMap<>();
TreeSet<Integer> set = new TreeSet<>();
set.add(20);
set.add(10);
set.add(30);
set.add(50);
set.add(70);
set.add(60);
set.add(90);
set.addAll(Arrays.asList(22,33,44,55));
lhm.put("A",set);
System.out.println(lhm);
}
Related
I have a question regarding the initiation of ArrayList in Java.
As far as I know I have to specify the type of my ArrayList when initialize it.
For example:
ArrayList<String> names = new ArrayList<String>();
or
ArrayList<String> names = new ArrayList<>();
However, when I want to write a code to return an ArrayList of List,
which is from the values of a map
Map<String, List> map = new HashMap<>();
If I tried to use the following, error happens
return new ArrayList<>(map.values())
or
return new ArrayList<List<String>>(map.values())
Instead, I can only use the one, without the <>.
return new ArrayList(map.values())
Could anyone let me know when I should or should not use the <> when I initialize an ArrayList(or any other objects)?
The original code is as written below
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList<>();
Map<String, List> res = new HashMap<>();
for (String s : strs) {
char[] charArray = s.toCharArray();
Arrays.sort(charArray);
String key = String.valueOf(charArray);
if (!res.containsKey(key)) res.put(key, new ArrayList());
res.get(key).add(s);
}
return new ArrayList<List<String>>(res.values());
}
public List<List<String>> groupAnagrams(String[] strs) {
...
Map<String, List> res = new HashMap<>();
...
res.put(key, new ArrayList());
...
return new ArrayList<List<String>>(res.values());
}
The problem here is that res.values() isn't a Collection<List<String>>, which is what would be required: it's a Collection<List>.
The elements of res.values() are raw types: you've used List without specifying the type parameters.
Raw types disable type checking, meaning you can end up putting things into collections with types you don't want.
Every time you use a generic type, make sure it has type parameters (or diamonds, if allowed:
public List<List<String>> groupAnagrams(String[] strs) {
...
Map<String, List<String>> res = new HashMap<>();
...
res.put(key, new ArrayList<>());
...
return new ArrayList<>(res.values());
}
Because the type of map value is List , but you define the type of list value is string.
And suggest use guava Multimap instead of Map<String ,List>
I am trying to compare the Key value pairs of an hash map where the value order is not same as i am reading the map1 from one source and map2 from another source.
The keys will be same but the order list will be in a different order.
The comparison is resulting fail, which i need to fix it
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
public class TestClass {
private static Map<String, List<String>> tempMap;
private static Map<String, List<String>> tempMap1;
private static Map<String, List<String>> tempMap2;
private static Map<String, List<String>> tempMap3;
public static Map<String, List<String>> practiceMap(){
tempMap = new HashMap<String, List<String>>();
List<String> completeDateKey = new ArrayList<>();
List<String> statusKey = new ArrayList<String>();
List<String> completeDateValue = new ArrayList<String>();
List<String> statusValue = new ArrayList<String>();
ArrayList<String> key = new ArrayList<String>(Arrays.asList("Complete Date", "Status"));
ArrayList<String> completedate = new ArrayList<String>(Arrays.asList("", "11/15/2019"));
ArrayList<String> status = new ArrayList<String>(Arrays.asList("NEW", "CLOSE"));
completeDateKey.add(key.get(0));
statusKey.add(key.get(1));
completeDateValue.addAll(completedate);
statusValue.addAll(status);
tempMap.put(completeDateKey.toString(), completeDateValue);
tempMap.put(statusKey.toString(), statusValue);
return tempMap;
}
public static Map<String, List<String>> practiceMap1(){
tempMap1 = new HashMap<String, List<String>>();
List<String> completeDateKey = new ArrayList<>();
List<String> statusKey = new ArrayList<String>();
List<String> completeDateValue = new ArrayList<String>();
List<String> statusValue = new ArrayList<String>();
ArrayList<String> key = new ArrayList<String>(Arrays.asList("Complete Date", "Status"));
ArrayList<String> completedate = new ArrayList<String>(Arrays.asList("11/15/2019", ""));
ArrayList<String> status = new ArrayList<String>(Arrays.asList("CLOSE", "NEW"));
completeDateKey.add(key.get(0));
statusKey.add(key.get(1));
completeDateValue.addAll(completedate);
statusValue.addAll(status);
tempMap1.put(completeDateKey.toString(), completeDateValue);
tempMap1.put(statusKey.toString(), statusValue);
return tempMap1;
}
public static void comparisionTest() {
tempMap3 = new HashMap<String, List<String>>();
tempMap2 = new HashMap<String, List<String>>();
tempMap2 = practiceMap();
tempMap3 = practiceMap1();
System.out.println("map 1 is " + tempMap2);
System.out.println("map 2 is " + tempMap3);
int size = practiceMap().size();
System.out.println(size);
if(tempMap2.equals(tempMap3) == true) { System.out.println("Successful"); }
else { System.out.println("failed"); }
}
public static void main(String[] args) {
new TestClass().comparisionTest();
}
}
How can i fix this so my comparision is successful
What you are looking for is called data normalization (in a broad sense).
Meaning: when you want to compare data in meaningful ways, you have to ensure that all data you look at is "organized" the same way.
In your case: if "equal" means: the same pairs of keys, and same content (ignoring order), then you can easily normalized that, for example by:
sorting the hash keys (when you iterate the hash keys in lexicographical order, well, you have a defined order)
sorting the lists
You could either do that "on the fly" (within a Comparator implementation for example), or by explicitly copying your data into such "ordered" collections.
If your lists do not have duplicates in them you could use sets since sets of the same values compare equally without regard to order.
Set<String> set1 = new LinkedHashSet<>();
set1.add("Alpha");
set1.add("Beta");
set1.add("Gamma");
Set<String> set2 = new LinkedHashSet<>();
set2.add("Gamma");
set2.add("Beta");
set2.add("Alpha");
Map<String, Set<String>> map1 = Map.of("A", set1);
Map<String, Set<String>> map2 = Map.of("A", set2);
System.out.println(set1.equals(set2)); // true
System.out.println(map1.equals(map2)); // true
I've got an ArrayList that looks like this:
ArrayList<String> item;
item [0] --> boom
item [1] --> pow
item [2] --> bang
item [3] --> zing
Now what I'm trying to do is take each item and create an empty ArrayList of strings with that item's name. For instance, the result would be
ArrayList<String> boom;
ArrayList<String> pow;
ArrayList<String> bang;
ArrayList<String> zing;
Sorry if this is a simple answer, but I'm still learning.
If I understand your question, then you might use a Map<String, ArrayList<String>> map, check if the heading is already present (and if it isn't create a new ArrayList<>). Something like,
Map<String, List<String>> headings = new HashMap<>();
// perform processing in a loop, for each heading...
String heading = "Example";
String content = "Body";
// ...
if (!headings.containsKey(heading)) {
headings.put(heading, new ArrayList<>());
}
List<String> bodies = headings.get(heading);
bodies.add(content);
// .. iterate heading
or you might prepopulate the headings map like
List<String> nameList = Arrays.asList("boom", "pow", "bang");
Map<String, List<String>> headings = new HashMap<>();
for (String name : nameList) {
headings.put(name, new ArrayList<>());
}
// ...
In programming language variable names is used to refers a stored value in computer memory. So a variable name can be considered as a key to access the value stored in computer memory. The standard data structure Map have the similar key value structure. So we can user Map here - "boom" as a key and new ArrayList<String>() as an value.
Suppose you have all the names (that is boom, pow, bang) in the nameList -
ArrayList nameList = new ArrayList(){{
add("boom");
add("pow");
add("bang");
}};
Now you want to create 3 ArrayList of Stirng by the name given in nameList. So you put them in a Map<String, List<String> like this -
Map<String, List<String> > vars = new HashMap<String, List<String>>();
for(int i=0; i<nameList.size(); i++){
String key = nameList.get(i);
List<String> value = new ArrayList<String>();
vars.put(key, value);
}
The complete cod can be -
import java.util.*;
public class ArrayListFromNameList {
public static void main(String[] args){
List<String> nameList = new ArrayList<String>(){{
add("boom");
add("pow");
add("bang");
}};
Map<String, List<String> > vars = new HashMap<String, List<String>>();
for(int i=0; i<nameList.size(); i++){
String key = nameList.get(i);
List<String> value = new ArrayList<String>();
vars.put(key, value);
}
}
/* Use the Map vars like this -
* vars.get("boom") --> will reuturns you an ArrayList<String>();
* similarly vars.get("pow") --> will returns you an ArrayList<String>();
*/
}
How would I add all the elements of a Set<<Set<String>> var to an ArrayList<<ArrayList<String>>? Of course I'm aware of the naive approach of just adding them.
private static ArrayList<ArrayList<String>> groupAnagrams(ArrayList<String> words){
ArrayList<ArrayList<String>> groupedAnagrams = new ArrayList<>();
AbstractMap<String, String> sortedWords = new HashMap<>();
Set<Set<String>> sameAnagramsSet = new HashSet<>();
for(String word : words){
char[] wordToSort = word.toCharArray();
Arrays.sort(wordToSort);
sortedWords.put(word, new String(wordToSort));
}
for(Map.Entry<String, String> entry: sortedWords.entrySet() ){
Set<String> sameAnagrams = new HashSet<>();
sameAnagrams.add(entry.getKey());
for(Map.Entry<String, String> toCompare : sortedWords.entrySet()){
if(entry.getValue().equals(toCompare.getValue())){
sameAnagrams.add(toCompare.getKey());
}
}
if(sameAnagrams.size()>0){
sameAnagramsSet.add(sameAnagrams);
}
}
//-->this line does not work! return new ArrayList<ArrayList<String>>(sameAnagramsSet);
}
With Java 8, you can do:
return sameAnagramsSet.stream()
.map(ArrayList::new)
.collect(toList());
although it returns a List<ArrayList<String>>.
What it does:
.stream() returns a Stream<Set<String>>
.map(ArrayList::new) is equivalent to .map(set -> new ArrayList(set)) and basically replaces each set by an array list
collect(toList()) places all the newly created lists in one list
Since you want to convert each element from a Set to an ArrayList, you'll have to do at least a little of this with an explicit loop, I think (unless you're using Java 8 or a third-party library):
Set<Set<String>> data = . . .
ArrayList<List<String>> transformed = new ArrayList<List<String>>();
for (Set<String> item : data) {
transformed.add(new ArrayList<String>(item));
}
Note that I changed the type of the transformed list from ArrayList<ArrayList<String>> to ArrayList<List<String>>. Generally it's preferable to program to an interface, but if you really need a list that must contain specifically instances of ArrayList, you can switch it back.
you have two LinkedHashMaps
Map m1 = new LinkedHashMap();
m1.put("1","One");
m1.put("3","Three");
Map m2 = new LinkedHashMap();
m2.put("2","Two");
m2.put("4","Four");
Find keys from both the Linked HashMap and store it in a list alternatively.
The list should contain 1,2,3,4.
Really sounds like homework, so I won't give you the exact code. I think the answers so far are wrong, as they don't interleave. Try this:
Get an Iterator iterator1 for the first map.
Get an Iterator iterator2 for the second map.
Use a while loop and ask for the next element in iterator1 and iterator2. The rest is for you to figure out.
This is solution:
List list = new ArrayList();
list.addAll(m1.keySet());
list.addAll(m2.keySet());
Collections.sort(list);
You can create a list and add both keySets from your maps, like so:
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map m1 = new LinkedHashMap();
m1.put("1","One");
m1.put("3","Three");
Map m2 = new LinkedHashMap();
m2.put("2","Two");
m2.put("4","Four");
List<String> list = new ArrayList<String>();
list.addAll(m1.keySet());
list.addAll(m2.keySet());
for(String s : list) {
System.out.println(s);
}
}
}