Two-dimensional ArrayList - java

Just a very small question... I seem to run into too much complexity here: I have to realize an index-structure like {42, someString}. I tried:
Object entry[][] = new Object[1][1];
ArrayList<Object> my_list = new ArrayList<Object>();
However that looks really strange. Isn't there a better much simpler solution to just store some Integer and a String? I need to perfrom search for the Strings and return the Integer... so I thought Collections and ArrayLists are good friends in the Java API.

Solution: use a Map
Uhm, do you perhaps need a Map?
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Some String", 42);
// or, more correctly:
map.put("Some String", Integer.valueOf(42));
You can search it using
Integer result = map.get("Some String");
Reference: Sun Java Tutorial > Collection Trail > Interfaces > The Map Interface
Fixing the OP's Code
BTW, the code in the question is flawed. Here's how you would do it if you wanted to use a List of object arrays (which you shouldn't):
// single dimension, not multi-dimension
Object[] entry = new Object[]{"Some String",Integer.valueOf(42)};
// use interface as variable, not implementation type
// generic type is object array, not object
List<Object[]> myList = new ArrayList<Object[]>();
// add array to list
myList.add(entry);
Now you could search like this:
for(final Object[] candidate : myList){
if("Some String".equals(candidate[0])){
System.out.println("Result: " + candidate[1]);
break;
}
}
However, this is just for reference, don't do it this way. The Collections Framework contains solutions for almost all standard cases. Use a Map.

Make a tuple class
public Class IntegerStringTuple {
private Integer number;
private String string;
//setters and getters etc.
}

If I understand correctly you should use a Map.
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(42, "someString");
String str = map.get(42);

Simply use a HashMap
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("foo",42);

why not use a map?
Map<String,Object>

It sounds like you want a Map

I would use a Map. Maps are used to store key value pairs.
Map<String, Integer> map = new HashMap<String, Integer>();

Map may not be used instead of an ArrayList when you require the order to be maintained.

ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
arr2.add(1);
arr2.add(2);
arr2.add(3);
arr1.add(arr2);
for(int i=0;i<arr1.size();i++){
System.out.println("i:"+arr1.get(i));
for(int j=0;j<((ArrayList)arr1.get(i)).size();j++){
System.out.println("j:"+((ArrayList)arr1.get(i)).get(j));
}
}
output: i:[1, 2, 3]
j:1
j:2
j:3

ArrayList<String> lcname = new ArrayList<String>();
lcname.add(cname);
ArrayList<String> lsize = new ArrayList<String>();
lsize.add(size);
Dictionary dictionary = new Hashtable();
Hashtable<String, ArrayList<ArrayList>> hashtable =
new Hashtable<String, ArrayList<ArrayList>>();
hashtable.put(fname, new ArrayList<>());
hashtable.get(fname).add(lcname);
hashtable.get(fname).add(lsize);
System.out.println(hashtable);
Here is the code for dictionaries of list(list).
OUTPUT
{file name=[[column name], [size]]}

Related

How to convert a Set<Set> to an ArrayList<ArrayList>

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.

Creating Map using put() method

I am trying to create a dictionnary in a <K, List<V>> format.
private static Map<String, Collection<String>> dict = new HashMap<String, Collection<String>>();
Using new HashMap<>(); or new HashMap<String, ArrayList<String>>(); throws incompatible data types error
I need a dictionary similar to the one below.
a: apple, ajar, axe, azure
b: ball, bat, box
d: dam, door, dish, drown, deer, dare
u: urn, umbrella
y: yolk
To do this, I worte below code. put() returns incompatible paramters compilation error. What is the right way to use put() for this example?
dict.put("a", "apple");
dict.put("a", "ajar");
.
.
.
dict.put("u", "umbrella");
dict.put("y", "yolk");
You need to place a List as the value to the map, for example:
List<String> listA = Arrays.asList("apple", "ajar", "axe", "azure");
dict.put("a", listA);
Alternatively, you can use guava Multimap which allows more than one value to be mapped to a given key.
This is because you need to put an arrayList in the value as your Map declaration is Map<String, Collection<String>> so it cannot take Map<String, String>.
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
dict.put("a",list );
As per java 7 you can do it using diamond operator so you can create a map as,
List<String, List<String>> = new ArrayList<>();
What you need is this;
List al = new ArrayList<String>();
al.add("apple");
al.add("ajar");
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
hm.put("a", al);
System.out.println(hm.get("a"));
This is because, when you use;
private static Map<String, Collection<String>>
You need a Collection like a List. DoNOT insert Objects as Strings
You can only follow the definition you have done :
Map<String, Collection<String>> implies you use dict.put(a,b) with a being a String and b a Collection.
You're trying to put a String as a value that's your problem.
You may want to do something like that :
Collection col = dict.get("a");
if (col == null) {
col = new ArrayList();
}
col.add("apple");
dict.put("a",col);
I would first change the type of the dictionary to
private static Map<Character, ArrayList<String>> dict = new HashMap<>();
It'll allow easier putting of array lists as generics are not covariant.
For each letter, create:
ArrayList<String> myList=new ArrayList<>();
and put() it to dict with
dict.put(myList);
Then you can add words with:
dict.get(letter).put(word);
Your exact need is MultiMap feature of apache-commons
MultiMap dict = new MultiHashMap();
dict.put("a", "apple");
dict.put("a", "ajar");
.
.
.
dict.put("u", "umbrella");
dict.put("y", "yolk");

How can I store HashMap<String, ArrayList<String>> inside a list?

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];
}

How to create and push dynamic elements in HashMap

static Map<Integer,HashMap<String,HashMap<String,String>>> maps = new HashMap<Integer, HashMap<String,HashMap<String,String>>>();
I want to insert the elements inside the HashMap I declared above , the inner most hashmap has values ready which I can use , now I am using it like ,
static Map<String,String> values = new HashMap<String, String>();
maps.put(1, new HashMap<<new String("")>, values>());
How can I achieve this ?
static Map<String,String> values1 = new HashMap<String,String>();
static Map<String,Map<String,String>> values2 = new HashMap<String,Map<String,String>>();
values2.put("", values1);
maps.put(1,values2);
btw, if you have java 7, you can use:
Map<String,String> values1 = new HashMap<>();
and so on for others
In cases you have map inside a map (inside a map), consider using Apache MultiKeyMap.
Coding will be more intuitive
It will improve the readability of your code
It will prevent many if(map.get(key) != null) blocks you will probably have in your code.
Why not to have instance of HashMap. When you wan to insert new value, you need to have Integer, String, String key and String value.
You continuously select nested HashMaps according to keys and then insert value to the most inner HashMap.
map.get(key1).get(key2).insert(key3, value)

Return HashMap added to List<Object>

I have a problem in JAVA when i'm trying to return a HashMap that I have added to a list of type: List<Object>. I know I can use other type of lists, but I need to use List<Object>
List<Object> listOfObjects = new ArrayList<Object>();
HashMap<String, String> hashmap = new HashMap<String,String>();
hashmap.put("x", "foo");
hashmap.put("y", "bar");
listOfObjects.add(hashmap);
for (int i = 0; i < listOfObjects.size(); i++) {
System.out.println(listOfObjects.get(i));
}
I have added my hashmap to my listOfObject, but how do I get the HashMap from the listOfObject such that I can use the HashMap-commands. fx: hashmap.get("x) and it will return "foo".
Normally i thought i could just write: listOfObjects.get(0).get("x") and it would return "foo" but that does not work.
If anyone know another work around that's find but I just need to use a List.
Normally i thought i could just write: listOfObjects.get(0).get("x") and it would return "foo" but that does not work.
No, it wouldn't - because the type of listOfObjects.get(0) is just Object. How do you expect the compiler to know that it's meant to be a map?
You can use:
HashMap<String, String> map = (HashMap<String, String>) listOfObjects.get(0);
// Use map...
... but be aware that due to the nature of generics in Java, that cast isn't really ensuring that all the key/value pairs in the map are "string to string". The cast would work even if you'd originally used:
Map<Integer, Integer> badMap = new HashMap<Integer, Integer>();
badMap.put(0, 10);
listOfObjects.add(badMap);
You'll get a warning for this, but it's important to understand what it means. It's not clear what your use case is, but if you can make it more strongly typed (perhaps create a new class which contains a Map<String, String>?) that would be good. Is every element of your list going to be a map? If so, why are you using List<Object> rather than a more strongly-typed list? If some elements aren't going to be maps, how can you tell which ones will be? (These are the sort of things you should be thinking about carefully.)
I hope this will help u..
List<Object> listOfObjects = new ArrayList<Object>();
HashMap<String, String> hashmap = new HashMap<String,String>();
hashmap.put("x", "foo");
hashmap.put("y", "bar");
listOfObjects.add(hashmap);
for (int i = 0; i < listOfObjects.size(); i++) {
System.out.println(((HashMap<String, String>)listOfObjects.get(i)).get("x"));
}
Normally as your list is of type of object . so first cast it to HashMap type and then get the value from map
please notice the following code
System.out.println(((HashMap<String, String>)listOfObjects.get(i)).get("x"));

Categories

Resources