Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?
Please do help me, also by telling (if there is no way) any other way to implement the storage of three values with one as the key?
You could:
Use a map that has a list as the value. Map<KeyType, List<ValueType>>.
Create a new wrapper class and place instances of this wrapper in the map. Map<KeyType, WrapperType>.
Use a tuple like class (saves creating lots of wrappers). Map<KeyType, Tuple<Value1Type, Value2Type>>.
Use mulitple maps side-by-side.
Examples
1. Map with list as the value
// create our map
Map<String, List<Person>> peopleByForename = new HashMap<>();
// populate it
List<Person> people = new ArrayList<>();
people.add(new Person("Bob Smith"));
people.add(new Person("Bob Jones"));
peopleByForename.put("Bob", people);
// read from it
List<Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs[0];
Person bob2 = bobs[1];
The disadvantage with this approach is that the list is not bound to exactly two values.
2. Using wrapper class
// define our wrapper
class Wrapper {
public Wrapper(Person person1, Person person2) {
this.person1 = person1;
this.person2 = person2;
}
public Person getPerson1() { return this.person1; }
public Person getPerson2() { return this.person2; }
private Person person1;
private Person person2;
}
// create our map
Map<String, Wrapper> peopleByForename = new HashMap<>();
// populate it
peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"),
new Person("Bob Jones"));
// read from it
Wrapper bobs = peopleByForename.get("Bob");
Person bob1 = bobs.getPerson1();
Person bob2 = bobs.getPerson2();
The disadvantage to this approach is that you have to write a lot of boiler-plate code for all of these very simple container classes.
3. Using a tuple
// you'll have to write or download a Tuple class in Java, (.NET ships with one)
// create our map
Map<String, Tuple2<Person, Person> peopleByForename = new HashMap<>();
// populate it
peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith",
new Person("Bob Jones"));
// read from it
Tuple<Person, Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs.Item1;
Person bob2 = bobs.Item2;
This is the best solution in my opinion.
4. Multiple maps
// create our maps
Map<String, Person> firstPersonByForename = new HashMap<>();
Map<String, Person> secondPersonByForename = new HashMap<>();
// populate them
firstPersonByForename.put("Bob", new Person("Bob Smith"));
secondPersonByForename.put("Bob", new Person("Bob Jones"));
// read from them
Person bob1 = firstPersonByForename["Bob"];
Person bob2 = secondPersonByForename["Bob"];
The disadvantage of this solution is that it's not obvious that the two maps are related, a programmatic error could see the two maps get out of sync.
No, not just as a HashMap. You'd basically need a HashMap from a key to a collection of values.
If you're happy to use external libraries, Guava has exactly this concept in Multimap with implementations such as ArrayListMultimap, HashMultimap, LinkedHashMultimap etc.
Multimap<String, Integer> nameToNumbers = HashMultimap.create();
System.out.println(nameToNumbers.put("Ann", 5)); // true
System.out.println(nameToNumbers.put("Ann", 5)); // false
nameToNumbers.put("Ann", 6);
nameToNumbers.put("Sam", 7);
System.out.println(nameToNumbers.size()); // 3
System.out.println(nameToNumbers.keySet().size()); // 2
Another nice choice is to use MultiValuedMap from Apache Commons. Take a look at the All Known Implementing Classes at the top of the page for specialized implementations.
Example:
HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()
could be replaced with
MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();
So,
map.put(key, "A");
map.put(key, "B");
map.put(key, "C");
Collection<String> coll = map.get(key);
would result in collection coll containing "A", "B", and "C".
Take a look at Multimap from the guava-libraries and its implementation - HashMultimap
A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.
I use Map<KeyType, Object[]> for associating multiple values with a key in a Map. This way, I can store multiple values of different types associated with a key. You have to take care by maintaining proper order of inserting and retrieving from Object[].
Example:
Consider, we want to store Student information. Key is id, while we would like to store name, address and email associated to the student.
//To make entry into Map
Map<Integer, String[]> studenMap = new HashMap<Integer, String[]>();
String[] studentInformationArray = new String[]{"name", "address", "email"};
int studenId = 1;
studenMap.put(studenId, studentInformationArray);
//To retrieve values from Map
String name = studenMap.get(studenId)[1];
String address = studenMap.get(studenId)[2];
String email = studenMap.get(studenId)[3];
HashMap<Integer,ArrayList<String>> map = new HashMap<Integer,ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
map.put(100,list);
If you use Spring Framework. There is: org.springframework.util.MultiValueMap.
To create unmodifiable multi value map:
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
Or use org.springframework.util.LinkedMultiValueMap
The easiest way would be to use a google collection library:
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class Test {
public static void main(final String[] args) {
// multimap can handle one key with a list of values
final Multimap<String, String> cars = ArrayListMultimap.create();
cars.put("Nissan", "Qashqai");
cars.put("Nissan", "Juke");
cars.put("Bmw", "M3");
cars.put("Bmw", "330E");
cars.put("Bmw", "X6");
cars.put("Bmw", "X5");
cars.get("Bmw").forEach(System.out::println);
// It will print the:
// M3
// 330E
// X6
// X5
}
}
maven link: https://mvnrepository.com/artifact/com.google.collections/google-collections/1.0-rc2
more on this: http://tomjefferys.blogspot.be/2011/09/multimaps-google-guava.html
Just for the record, the pure JDK8 solution would be to use Map::compute method:
map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
Such as
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
put(map, "first", "hello");
put(map, "first", "foo");
put(map, "bar", "foo");
put(map, "first", "hello");
map.forEach((s, strings) -> {
System.out.print(s + ": ");
System.out.println(strings.stream().collect(Collectors.joining(", ")));
});
}
private static <KEY, VALUE> void put(Map<KEY, List<VALUE>> map, KEY key, VALUE value) {
map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
}
with output:
bar: foo
first: hello, foo, hello
Note that to ensure consistency in case multiple threads access this data structure, ConcurrentHashMap and CopyOnWriteArrayList for instance need to be used.
Yes and no. The solution is to build a Wrapper clas for your values that contains the 2 (3, or more) values that correspond to your key.
Yes, this is frequently called a multimap.
See: http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multimap.html
Using Java Collectors
// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
where Department is your key
String key= "services_servicename"
ArrayList<String> data;
for(int i = 0; i lessthen data.size(); i++) {
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
servicesNameHashmap.put(key,data.get(i).getServiceName());
mServiceNameArray.add(i,servicesNameHashmap);
}
I have got the Best Results.
You just have to create new HashMap like
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
in your for loop. It will have same effect like same key and multiple values.
import java.io.*;
import java.util.*;
import com.google.common.collect.*;
class finTech{
public static void main(String args[]){
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("1","11");
multimap.put("1","14");
multimap.put("1","12");
multimap.put("1","13");
multimap.put("11","111");
multimap.put("12","121");
System.out.println(multimap);
System.out.println(multimap.get("11"));
}
}
Output:
{"1"=["11","12","13","14"],"11"=["111"],"12"=["121"]}
["111"]
This is Google-Guava library for utility functionalities. This is the required solution.
I could not post a reply on Paul's comment so I am creating new comment for Vidhya here:
Wrapper will be a SuperClass for the two classes which we want to store as a value.
and inside wrapper class, we can put the associations as the instance variable objects for the two class objects.
e.g.
class MyWrapper {
Class1 class1obj = new Class1();
Class2 class2obj = new Class2();
...
}
and in HashMap we can put in this way,
Map<KeyObject, WrapperObject>
WrapperObj will have class variables: class1Obj, class2Obj
You can do it implicitly.
// Create the map. There is no restriction to the size that the array String can have
HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();
//initialize a key chosing the array of String you want for your values
map.put(1, new String[] { "name1", "name2" });
//edit value of a key
map.get(1)[0] = "othername";
This is very simple and effective.
If you want values of diferent classes instead, you can do the following:
HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();
Can be done using an identityHashMap, subjected to the condition that the keys comparison will be done by == operator and not equals().
I prefer the following to store any number of variables without having to create a separate class.
final public static Map<String, Map<String, Float>> myMap = new HashMap<String, Map<String, Float>>();
I am so used to just doing this with a Data Dictionary in Objective C. It was harder to get a similar result in Java for Android. I ended up creating a custom class, and then just doing a hashmap of my custom class.
public class Test1 {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addview);
//create the datastring
HashMap<Integer, myClass> hm = new HashMap<Integer, myClass>();
hm.put(1, new myClass("Car", "Small", 3000));
hm.put(2, new myClass("Truck", "Large", 4000));
hm.put(3, new myClass("Motorcycle", "Small", 1000));
//pull the datastring back for a specific item.
//also can edit the data using the set methods. this just shows getting it for display.
myClass test1 = hm.get(1);
String testitem = test1.getItem();
int testprice = test1.getPrice();
Log.i("Class Info Example",testitem+Integer.toString(testprice));
}
}
//custom class. You could make it public to use on several activities, or just include in the activity if using only here
class myClass{
private String item;
private String type;
private int price;
public myClass(String itm, String ty, int pr){
this.item = itm;
this.price = pr;
this.type = ty;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getType() {
return item;
}
public void setType(String type) {
this.type = type;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
We can create a class to have multiple keys or values and the object of this class can be used as a parameter in map.
You can refer to https://stackoverflow.com/a/44181931/8065321
Apache Commons collection classes can implement multiple values under same key.
MultiMap multiMapDemo = new MultiValueMap();
multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");
System.out.println(multiMapDemo.get("fruit"));
Maven Dependency
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
Related
I have a list of maps. Which I cannot predict the key of each map. key can be an any two digits number which will change acordingly to the request.But values contains unique values from request to request.Now I need to sort this list of maps according to the value of each key. I've already tried something like bellow,
List<Map<String,String>> listOfMaps = new ArrayList<>();
Map<String,String> map1 = new HashMap<>();
Map<String,String> map2 = new HashMap<>();
map1.put("key1","value1");
map2.put("key2","value1");
listOfMaps.add(map1);
listOfMaps.add(map2);
sort(listOfMaps);
Collections.sort(listOfMaps, new Comparator<Map<String, String>>() {
public int compare(final Map<String, String> o1, final Map<String, String> o2) {
return o1.get("key").compareTo(o2.get("key"));
}
});
Since "key" can be differ from map to map, seems I couldnt use the above code.
I've also tried these examples.
How to Sort a List of Maps by two Categories?
Sorting list of maps based on a value
Since I'm cannot predict the key, I couldnt find an answer from these post.Can any one help with this?.
The below example should work, under the assumption that each map element contains only one entry:
List<Map<String, String>> list = new ArrayList<>();
//Add entries
Collections.sort(list, new Comparator<Map<String, String>>() {
public int compare(Map<String, String> o1, Map<String, String> o2) {
Collection<String> values1 = o1.values();
Collection<String> values2 = o2.values();
if(!values1.isEmpty() && !values2.isEmpty()){
return values1.iterator().next().compareTo(values2.iterator().next());
}else{
return 0;
}
}
});
While it is occasionally necessary to create a Map with only one key and one value (Collections.singletonMap is used for this), it doesn't look like Map is appropriate for your situation. It makes much more sense to use a custom class with two fields, something like this:
// This is immutable. You may prefer to make fields non-final and add setters.
// You may also want to override equals() and hashCode().
final class StringPair {
private final String key;
private final String value;
StringPair(String key, String value) {
this.key = key;
this.value = value;
}
#Override
public String toString() {
return "[" + key + ", " + value + "]";
}
}
Then you can do:
List<StringPair> list = new ArrayList<>();
list.add(new StringPair("K2", "V2"));
list.add(new StringPair("K1", "V1"));
Collections.sort(list, new Comparator<StringPair>()
#Override
public int compare(StringPair o1, StringPair o2) {
return o1.value.compareTo(o2.value);
}
});
System.out.println(list); // Prints [[K1, V1], [K2, V2]]
My last attempt was poorly explained, so recreated with hopefully a clearer explanation.
I have a Collection that has the following data structure.
LinkedHashMap<String, String> currentHashMap = new LinkedHashMap<String, String>();
currentHashMap.put("id","12345");
currentHashMap.put("firstName","John");
currentHashMap.put("lastName","Doe");
haystack.add(currentHashMap);
*repeat for roughly 250,000 more entries
I need to search the HashMaps within each list entry, check if the key exists, and if it has the corresponding value. If it does, I want to return all the values in that particular hashmap
This is the code that I'm currently using.
private TreeSet<String> searchWithinCollection(List<LinkedHashMap<String, String>> haystack, String needle, String needleKey) {
TreeSet<String> returnValueSet = new TreeSet<>();
for (LinkedHashMap<String, String> mappedData : haystack) {
System.out.println(mappedData.values());
for (Entry<String, String> specificData : mappedData.entrySet()) {
if (needleKey.equals(specificData.getKey()) && needle.equals(specificData.getValue())) {
//where I want to collect the values within the current hashmap, as it's satisfied the search criteria
//the current code would only return the current key/balue pair, even if all values were collected outside the for loop. Instead, I'd want to collect "12345", "John", "Doe" if needleKey = id and needle = 12345.
}
}
}
return returnValueSet;
}
What I'd want is if a key in the current collection equaled "id", and it's value equaled "12345", then I could returned all values within that particular collection (and to use the example above, would be "12345", "John", "Doe").
The best I can do is return the first key/value, which isn't very helpful obviously. Attempting to capture all values in mappedData outside the second for loop brought no result (either with creating a new instance of a Collection, clone, or what have you.). I also found nothing that could manually advance the pointer in the for each loop to manually capture all values in the Collection.
EDIT: If it helps, where there is a System.out.println(mappedData.values()); I can get the values I'm expecting, but only the id in the example is return if values() is accessed within the if statement.
You should not iterate over all the entries in a hashmap (currently, the loop for (Entry<String, String> specificData : mappedData.entrySet()) in your code. This defeats the purpose of maintaining a hashmap.
Instead, the inner loop should become
String potentialNeedle = mappedData.get(needleKey);
if (needle.equals(potentialNeedle))
returnValueSet.addAll(mappedData.values());
You're using the map as if it was a list of entries, which completely defeats the purpose of a map: quickly access to a value for a given key:
for (Map<String, String> mappedData : haystack) {
String value = mappedData.get(needleKey);
if (needle.equals(value)) {
returnValueSet.addAll(mappedData.values());
}
}
Maybe you should take redesign in account to improve performance. it could be smart to have a map for each field you want to search. instead of your haystack create your data-structure like that:
public class PersonDataManager {
private final Map<Integer, Map<String, String>> baseData;
private final Map<String, List<Integer>> firstNameLookupMap;
private final Map<String, List<Integer>> lastNameLookupMap;
public PersonDataManager(){
this.baseData = new HashMap<>();
this.firstNameLookupMap = new HashMap<>();
this.lastNameLookupMap = new HashMap<>();
}
public void addPerson(Integer id, String firstName, String lastName){
//try to find existing person to update:
Map<String, String> personMap = baseData.get(id);
if(personMap == null){
personMap = new HashMap<>();
baseData.put(id, personMap);
}
personMap.put("firstName", firstName);
personMap.put("lastName", lastName);
//add to lookup-maps
addLookupName(firstNameLookupMap, id, firstName);
addLookupName(lastNameLookupMap, id, lastName);
}
private static void addLookupName(Map<String, List<Integer>> nameMap, Integer id, String name){
//get existing list of the name:
List<Integer> idList = nameMap.get(name);
if(idList == null){
idList = new ArrayList<>();
}
if(!idList.contains(id)){
idList.add(id);
}
}
private List<Map<String, String>> searchByName(Map<String, List<Integer>> nameMap, String name){
List<Integer> matchingIds = nameMap.get(name);
List<Map<String, String>> result = new ArrayList<>();
if(matchingIds != null){
for(Integer id : matchingIds){
result.add(searchById(id));
}
}
return result;
}
public Map<String, String> searchById(Integer id){
return baseData.get(id);
}
public List<Map<String, String>> searchByFirstName(String name){
return searchByName(firstNameLookupMap, name);
}
public List<Map<String, String>> searchByLastName(String name){
return searchByName(lastNameLookupMap, name);
}
}
This way you can easily get a hashmap of a person using its id. if you need to search by firstname or lastname you can utilize the additional maps to get the matching person-ids. hope this helps
EDIT: Just implemented a class which does exactly what i think you might need. have fun ;)
I'm trying to remove similar strings from an ArrayList but I'm getting this error:
CurrentModificationException
and here is my method where I pass my original arrayList (old) and get a new list without redundant strings.
ArrayList<String> removeRed(ArrayList<String> old) throws IOException
{
ArrayList<String> newList = new ArrayList<String>();
for (int i=0; i< old.size(); i++)
{
if(newList.size() < 1)
{
newList.add(old.get(0));
} else{
for(Iterator<String> iterator = newList.iterator(); iterator.hasNext();) {
while(iterator.hasNext())
{
if(!ChopMD((String) iterator.next()).equals(ChopMD(old.get(i))))
{
newList.add(old.get(i));
Log.e("new algo", "" + old.get(i) );
}
}
}
}
}}
Note that my ChopMD() returns a particular string and it works fine.
It works fine for the first few strings, this it throws that exception. Any suggestion to resolve this issue would be appreciated it. Thanks.
If you have no problems with using the standard library (always preferable, why reinvent the wheel) try
List<String> uniques = new ArrayList<String>(new HashSet<String>(oldList));
The HashSet will only contain unique strings and the ArrayList constructor takes any Collection (including a HashSet) to build a list from.
Judging from your comments it seems like you are trying to implement an Associative Array with unique keys using an ArrayList. The better approach is to use a Map implementation like HashMap to pair IDs with their associated Strings.
Map<Integer, String> map = new HashMap<>();
map.put(1, "This string corresponds to ID=1");
map.put(3, "Donald Ducks Nephews");
map.put(7, "Is a Prime");
Then to get a value associated with an ID:
int key = someObject.getID();
String value = map.get(key);
All the Map implementations use unique keys so there is no need for you to check for redundant IDs, if you try to add a new (key,value) pair the value associated with the ID will be replaced if the map contains the key.
map.put(1, "New String");
String s = map.get(1); //s will no longer be "This string corresponds to ID=1"
If you don't want this behavior you have the choice of either subclassing one of the Map implementations to ignore .put(key, value) if the map contains key,value or delegating .put(key,value) to some other class.
Subclassing:
public class UniqueValueHashMap<K,V> extends HashMap<K, V>{
#Override
public V put(K key, V value) {
if (containsKey(key))
return null;
return super.put(key, value);
}
Delegating
public class SomeClass {
private Map<Integer, String> map = new HashMap<>();
// ...stuff this class does
public String put(int key, String value) {
if (map.containsKey(key))
return null;
return map.put(key, value);
}
// ...more stuff this class does
}
Delegation is the better approach, notice how you can change the map implementation (using maybe a TreeMap instead of HashMap) without introducing a new class where you override the .put(key,value) of TreeMap.
You can iterate much easier by this
for (String oldString : old){
for (String newString : newList){
}
}
Also you can use Set to have unique strings
Set<String> newList = new HashSet<String>();
Your error is because you are changing the list WHILE it is still iterated.
Can you guide me how can I sort Array List having Hash Map alphabatically?
JSONArray jArr2 = new JSONArray(jsonString2);
for(int i=0;i<jArr2.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
map.put("titleName",jArr2.getJSONObject(i).getString("titleName"))
programList.add(map);
}
Implement a Comparator<HashMap<String, String>> which just extracts the value assocated with the value key, then use Collections.sort method to sort your arraylist.
For e.g.:
class MyComparator implements Comparator<Map<String, String>>{
private final String key;
public MyComparator(String key)
{
this.key = key;
}
public int compare(Map<String, String> first,
Map<String, String> second)
{
// TODO: Null checking, both for maps and values
String firstValue = first.get(key);
String secondValue = second.get(key);
return firstValue.compareTo(secondValue);
}
}
Looking at your example, I don't think you need a Map to be involved at all. What you have is a list of Maps, where every Map only has one key, which is "titleName". Why not just have a list of titlenames? Then your code would look like this:
JSONArray jArr2 = new JSONArray(jsonString2);
List<String> titleNames = new ArrayList<>();
for (int i = 0; i < jArr2.length(); i++) {
titleNames.add(jArr2.getJSONObject(i).getString("titleName"))
}
You know that the list only contains titleNames, you don't need to complicate the data structure with Maps!
Then you can sort the list simply by using
Collections.sort(titleNames);
Note that this will work while the other answers that suggests Collections.sort() on the list of maps will not work. This is because titleNamees is a List of Strings, which implement Comparable (ie the sort() method knows how to order them with respect to each other), while Map does not implement comparable (as there are multiple ways to order Maps - number of entries, total number of bytes, etc).
Yes you can use Collections.sort(); with a custom comparator. Here is the doc.
Collections.sort(YOUR_ARRAY_LIST, new YourCustomComparator());
And this should be the class you must have
class YourCustomComparator implements Comparator<HashMap<String, String>> {
#Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
// check here your objects. lhs and rhs. compare them as you want
// return 1 if lhs is greater than rhs
// return 0 if ther are same
// return -1 otherwise
}
}
My hashmap stores the string as key and arraylist as the values. Now, I need to embed this into a list. That is, it will be of the following form:
List<HashMap<String, ArrayList<String>>>
These are the declarations I have used:
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
map.put(key,arraylist);
List<String> list = new ArrayList<String>();
Can anyone help me which method and how to use in the list to proceed storing my map into it?
Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?
List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.
You can easily do it like the above.
First, let me fix a little bit your declaration:
List<Map<String, List<String>>> listOfMapOfList =
new HashList<Map<String, List<String>>>();
Please pay attention that I used concrete class (HashMap) only once. It is important to use interface where you can to be able to change the implementation later.
Now you want to add element to the list, don't you? But the element is a map, so you have to create it:
Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();
Now you want to populate the map. Fortunately you can use utility that creates lists for you, otherwise you have to create list separately:
mapOfList.put("mykey", Arrays.asList("one", "two", "three"));
OK, now we are ready to add the map into the list:
listOfMapOfList.add(mapOfList);
BUT:
Stop creating complicated collections right now! Think about the future: you will probably have to change the internal map to something else or list to set etc. This will probably cause you to re-write significant parts of your code. Instead define class that contains you data and then add it to one-dimentional collection:
Let's call your class Student (just as example):
public Student {
private String firstName;
private String lastName;
private int studentId;
private Colectiuon<String> courseworks = Collections.emtpyList();
//constructors, getters, setters etc
}
Now you can define simple collection:
Collection<Student> students = new ArrayList<Student>();
If in future you want to put your students into map where key is the studentId, do it:
Map<Integer, Student> students = new HashMap<Integer, Student>();
Try the following:
List<Map<String, ArrayList<String>>> mapList =
new ArrayList<Map<String, ArrayList<String>>>();
mapList.add(map);
If your list must be of type List<HashMap<String, ArrayList<String>>>, then declare your map variable as a HashMap and not a Map.
First you need to define the List as :
List<Map<String, ArrayList<String>>> list = new ArrayList<>();
To add the Map to the List , use add(E e) method :
list.add(map);
class Student{
//instance variable or data members.
Map<Integer, List<Object>> mapp = new HashMap<Integer, List<Object>>();
Scanner s1 = new Scanner(System.in);
String name = s1.nextLine();
int regno ;
int mark1;
int mark2;
int total;
List<Object> list = new ArrayList<Object>();
mapp.put(regno,list); //what wrong in this part?
list.add(mark1);
list.add(mark2);**
//String mark2=mapp.get(regno)[2];
}