Hy!
I have a Treemap and i want to set all strings in the map to the ListView
Code:
TreeMap<String, Integer> map = json.getChannels(lv.getItemAtPosition(arg2).toString());
ListView lv2 = new ListView(Channellist.this);
Set st = map.keySet();
lv2.setAdapter(new ArrayAdapter<String>(Channellist.this,android.R.layout.simple_expandable_list_item_1,st));
My Problem is that the ArrayAdapter doesn't support a Set.
Are there any Solutions?
THX
Just create an ArrayList and all all the elements from the set. Pass this list.
ArrayList<String> l = new ArrayList<String>(st);
Now use l. Or just create an Array:
String[] array = (String[])set.toArray(new String[st.size()]);
EDIT: Added enhancement from comment.
EDIT2: Add #SupressWarnings("unchecked") to your function. I have to do this all the time when using external APIs that use pre-1.5 ungeneric code :).
Related
I have an array:
String[] a = {"abc","def","ghi"}
Now I want to store this array into my string arraylist
ArrayList<String> arr = new ArrayList<>();
so that it becomes like this:
[["abc","def","ghi"]]
I have tried this code but it doesn't work:
arr.add(Arrays.asList(a));
Please help me
Since Arrays.asList(a) returns List, to add it to your list you need to use addAll()
arr.addAll(Arrays.asList(a));
Instead of
arr.add(Arrays.asList(a));
But the result will be ["abc","def","ghi"]
If you want to achieve this [["abc","def","ghi"]] then define your ArrayList as
List<List<String>> arr = new ArrayList<>();
using arralist addAll() method we can do but,
Using arrayList is depricated approach , use Streams instead of it:
System.out.println(Collections.singletonList(Stream.of(new String[] {"abc","def","ghi"}).collect(Collectors.toList())));
will result in:
[[abc, def, ghi]]
Okay, so I'm fairly new to programming so apologies if this problem is really simple, I've created an ArrayList inside my Hash Map so that I can add more than one value into my hash map.
My code looks fine (to me) but theres an error on this line "mymap.add(module, new ArrayList>());" saying ( or [ expected.
Wasted way too much time trying to figure this out so thought I'd post here. Thanks in advance for any help. Also: yes I need to do it this way and no I can't use guava MultiMap.
public class hashArray {
HashMap<String, ArrayList<Integer>> mymap = new HashMap<String, ArrayList<Integer>>();
public hashArray() {}
public void addEntryHR( String module, Integer result ) {
mymap.add(module, new ArrayList<Integer>>());
There is a typo and a bug in your line:
// The typo is right here v
mymap.add(mod, new ArrayList<Integer>>());
Remove one of the > and change add to put:
mymap.put(mod, new ArrayList<Integer>());
The error you get, is about the typo. Fixing that typo will give you an error about add to be an unknown method.
You need to first get the list out from map object like below-
ArrayList<Integer> list = mymap.get(mod);
if (list==null){
//then create new ArrayList object and assign to list
list=new ArrayList<Integer>();
}
list.add(number); //adding new number to the list
mymap.put(mod,list); //storing in map
The problems
You create a new ArrayList in new ArrayList<Integer>>() (with contains a syntax error as well - a > too many), but never add number to it.
You are calling add on a HashMap, which doesn't have this method. For maps, it is called put.
Proposed solution
Please see the code below
Map<String, List<Integer>> myMap = new HashMap<>();
public void addEntryHR(String mod, Integer number) {
List<Integer> numbers = new ArrayList<>();
numbers.add(number);
myMap.put(mod, numbers);
}
Other remarks
Use interfaces
It is advised to use the interfaces of the collections rather than the implementations. This means Map<String, String> myMap instead of HashMap<String, String> myMap and List<Integer> instead of ArrayList<Integer>.
Why do this? Because this allows you to be flexible in the collections you use and reduce maintenance effort. Say you change your mind and want to use LinkedList instead of ArrayList, then you just have to change one new ArrayList<>() to new LinkedList<>() instead of all the ArrayList variables used throughout the code.
I want to create a hashmap defined as HashMap<Character,ArrayList<String>>.
What I am trying to do is to read a set of strings which I am reading into a list.
From this list I want to generate this hashmap.
So if strings are something like this
Andy,Aman,Rocky,Ravi,Nick etc.
Map should be like
A->[Andy,Aman]
R->[Rocky,Ravi]
N->Nick
What I have tried is something like this
ArrayList<String> xlist= new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
HashMap<Character,ArrayList<String>> h = new HashMap<Character,ArrayList<String>>();
Scanner s = new Scanner(System.in);
for(String sin : list){
Character x =sin.charAt(0);
//System.out.println(sin.charAt(0));
if(h.containsKey(x)){
h.get(x).add(sin);
//xlist.clear();
//xlist = h.get(x);
//xlist.add(sin);
//h.put(x,xlist.clone());
}
else{
xlist.clear();
xlist.add(sin);
h.put(x,xlist);
}
}
When I print the hashmap, I get this
{A=[Ravi, Rocky], R=[Ravi, Rocky], N=[Ravi, Rocky]}
I understand , that all the lists in values are being reflected from same copy of list, but I don't know , how to resolve it.
If you don't want to rewrite the loop, you can just change your last line within the else block so you won't change content of map on every iteration:
h.put(x,new ArrayList<String>(Arrays.asList(sin)));
You can also do it using Java 8 Streams which makes it much shorter:
Map<Character, List<String>> map = list.stream().collect(Collectors.groupingBy(d -> d.charAt(0)));
If you want to preserve the order of keys you can use it with LinkedHashMap:
Map<Character, List<String>> map = list.stream().collect(Collectors.groupingBy(d->d.charAt(0), LinkedHashMap::new, Collectors.toList()));
xlist is always the same list, even after you've put it in your hashmap. Whenever you hit a new letter, you clear every list in your hashmap, and add the current word to every list, because they're all the same list.
I'd rewrite your loop as:
for(String sin : list){
Character x =sin.charAt(0);
if(!h.containsKey(x)){
h.put(x, new ArrayList<String>());
}
h.get(x).add(sin);
}
I need to create a list with values of type - (long,String)
like -
ArrayList a = new ArrayList();
a.add(1L,branchName);
How can I do this because if I use list It will accept only int,String.
You should note that ArrayList's add(int,String) adds the String element in the given int index (if the index is valid). The int parameter is not part of the contents of the ArrayList.
Perhaps an ArrayList is not the correct choice for you. If you wish to map Long keys to String values, use Map<Long,String>.
Map<Long,String> a = new HashMap<> ();
a.put(1L,branchName);
You can define a custom class, e.g.
class IndexAndBranchName {
long index;
String branchName;
}
and then add instances of this to the ArrayList:
ArrayList<IndexAndBranchName> a = new ArrayList<>();
a.add(new IndexAndBranchName(index, branchName));
Whether you use this approach or something like Eran's depends upon what you need to use the list for subsequently:
If you want to look "branches" up by index, use a Map; however, you can only store a single value per key; you could use a Guava Multimap or similar if you want multiple values per key.
If you simply want all of the index/branch name pairs, you can use this approach.
You can use the below code for your question.
HashMap is also a better option , but if you want only ArrayList then use it.
List<Map<Object, Object>> mylist = new ArrayList<Map<Object, Object>>();
Map map = new HashMap<>();
map.put(1L, "BranchName");
mylist.add(map);
What I have is a HashMap<String, ArrayList<String>> called examList. What I want to use it for is to save grades of each course a person is attending. So key for this HashMap is couresID, and value is a ArrayList of all grades (exam attempts) this person has made.
The problem is I know how to work with array lists and hashmaps normally, but I'm not sure how to even begin with this example. So how would I, or example, add something to ArrayList inside HashMap?
You could either use the Google Guava library, which has implementations for Multi-Value-Maps (Apache Commons Collections has also implementations, but without generics).
However, if you don't want to use an external lib, then you would do something like this:
if (map.get(id) == null) { //gets the value for an id)
map.put(id, new ArrayList<String>()); //no ArrayList assigned, create new ArrayList
map.get(id).add(value); //adds value to list.
String courseID = "Comp-101";
List<String> scores = new ArrayList<String> ();
scores.add("100");
scores.add("90");
scores.add("80");
scores.add("97");
Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
myMap.put(courseID, scores);
Hope this helps!
First create HashMap.
HashMap> mapList = new HashMap>();
Get value from HashMap against your input key.
ArrayList arrayList = mapList.get(key);
Add value to arraylist.
arrayList.add(addvalue);
Then again put arraylist against that key value.
mapList.put(key,arrayList);
It will work.....
First you retreieve the value (given a key) and then you add a new element to it
ArrayList<String> grades = examList.get(courseId);
grades.add(aGrade);
Java 8+ has Map.compute for such cases:
examList.compute(courseId, (id, grades) ->
grades != null ? grades : new ArrayList<>())
.add(value);
First, you have to lookup the correct ArrayList in the HashMap:
ArrayList<String> myAList = theHashMap.get(courseID)
Then, add the new grade to the ArrayList:
myAList.add(newGrade)
Can also do this in Kotlin without using any external libraries.
var hashMap : HashMap<String, MutableList<String>> = HashMap()
if(hashMap.get(id) == null){
hashMap.put(id, mutableListOf<String>("yourString"))
} else{
hashMap.get(id)?.add("yourString")
}
HashMap<String, ArrayList<ObjectX>> objList = new HashMap<>();
if(objList.containsKey(key))
objList.get(key).add(Object1);
else
objList.put(key, new ArrayList<ObjectX>(Arrays.asList(Object1)));