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>();
*/
}
Related
I have a list of values which concatenates the method name with the class name.
Ex: method1#class1
Now, I want to create a map where the key is the class name and values is a list of method names. The sample code is as follows.
Map<String, List<String>> map = new HashMap<>();
List<String> name = new ArrayList<>();
name.add("method1#class1");
name.add("method2#class1");
name.add("method3#class2");
name.add("method4#class2");
So, based on the above example, I need to create a map that should contain
{class1 : [method1,method2]}
{class2 : [method3,method4]}
Can someone help to iterate the above list and add to the map?
You can use streams in combination with the groupingBy collector:
Map<String, List<String>> result = name.stream()
.map(s -> s.split("#")) // split string by '#'
.collect(
Collectors.groupingBy(arr -> arr[1], // second element is the key
Collectors.mapping(arr -> arr[0], // first element is the value
Collectors.toList()))); // collect values with the same key into a list
System.out.println(result); // {class2=[method3, method4], class1=[method1, method2]}
You could do something like this:
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> name = new ArrayList<String>();
name.add("method1#class1");
name.add("method2#class1");
name.add("method3#class2");
name.add("method4#class2");
for (String item : name) {
String[] split = item.split("#");
String className = split[1];
if(!map.containsKey(className))
map.put(className, new ArrayList<String>());
map.get(className).add(split[0]);
}
Good luck!
Clue about extracting method names from a class:
Class c = Example.class;
Method[] m = c.getDeclaredMethods();
for (Method method: m) {
System.out.println(method.getName());
}
I made all explanations in comments to the code:
Map<String, List<String>> map = new HashMap<>();
List<String> name = new ArrayList<>();
name.add("method1#class1");
name.add("method2#class1");
name.add("method3#class2");
name.add("method4#class2");
for(String nm : name) { // for each String from name list...
String[] splitted = nm.split("#"); // split this string on the '#' character
if(map.containsKey(splitted[1])) { // if result map contains class name as the key...
map.get(splitted[1]).add(splitted[0]); // get this key, and add this String to list of values associated with this key
} else { // if result map doesn't contain that class name as key...
map.put(splitted[1], new ArrayList<String>()); // put to map class name as key, initialize associated ArrayList...
map.get(splitted[1]).add(splitted[0]); // and add method name to ArrayList of values
}
}
List<Map<String, String>> personList = new ArrayList<HashMap<String, String>> ();
String tempcnic = SBox.getText().toString();
HashMap<String,String> temp = new HashMap<>();
for (int i = 0; i < personlistcopy.size(); i++) {
temp = personlistcopy.get(i);
if (temp.get(TAG_CNIC) == tempcnic) {
Toast.makeText(History.this, temp.get(TAG_CNIC), Toast.LENGTH_SHORT).show();
personList2.add(temp);
}
temp = null;
}
I have an ArrayList containing HashMaps,
HashMap contains 4 keys with corresponding values.
name
Cnic
Date
Time
Kindly help me in doing "Search and find all HashMaps in ArrayList with given cnic and add them to a new ArrayList. The new ArrayList will have all records with that cnic."
Here's how to do it with Java 8's stream:
List<Map<String, String>> personList = new ArrayList<>(); //Your list
List<Map<String,String>> filtered = personList.stream()
.filter(p -> "your_cnic".equals(p.get("cnic")))
.collect(Collectors.toList());
If you want case insensitive comparison, you can use equalsIgnoreCase instead of equals.
Here is non-stream solution (for Java 5, 6 and 7):
List<HashMap<String, String>> personList = new ArrayList<HashMap<String, String>>(); //Your list
List<HashMap<String,String>> filtered = new ArrayList<HashMap<String,String>>();
for(HashMap<String, String> person : personList){
if("your_cnic".equals(person.get("cnic"))){
filtered.add(person);
}
}
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.
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];
}
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);
}