How to access a single ArrayList in ArrayListMultiMap - java

I would like to get an entry from ArrayList in an ArrayListMultiMap. I am using Google Guava ArrayListMultimap and each key is associated with multiple array lists. For example, for the key1 I have 4 array lists, and each ArrayList contains 2 entries. I need to be able to access a particular ArrayList and get an entry from there so my question is how do I do it? Every time I try to access the value associated with the key it prints all 4 array lists but I need only one.
Multimap<String, ArrayList<String>> wordAsKey = ArrayListMultimap.create();
for (DictionaryEntries dict : DictionaryEntries.values()) {
ArrayList<String> list = new ArrayList<>();
String key = dict.getKey();
String partOfSpeech = dict.getPartOfSpeech();
String definition = dict.getDefinition();
list.add(partOfSpeech);
list.add(definition);
wordAsKey.put(key, list);
}
ArrayList<String> resultList = new ArrayList<>();
resultList.add(wordAsKey.get(word).toString());
System.out.println(resultList);
Prints
[[[noun, A set of pages.], [noun, A written work published in printed or electronic form.], [verb, To arrange for someone to have a seat on a plane.], [verb, To arrange something on a particular date.]]]
But I need it to print only [noun, A set of pages.]

you can try: get index value
int index = 0;
resultList.add(wordAsKey.get(word).get(index).toString());

Just do it like this -
ArrayList<String> list = (ArrayList<String>)wordAsKey.get(word);
String result = list.get(index);
System.out.println(result);
And you can check whether particular String is exist or not in List, then see below;
if(list.contains("search")){...}

Related

how to get substring items with in arraylist in java

I have arraylist of strings, I need to find the substrings among the items in same arraylist?
For example:
ArrayList<String> ar = new ArrayList();
ar.add("UserId"); //adding item to arraylist
ar.add("Directory");
ar.add("Username");
ar.add("PhoneNumber");
Here I want to find substring of items, basically I need output as UserId and Username from the list items. how can I do it can someone help me out.
you have two approaches:
ArrayList<String> ar = new ArrayList();
ar.add("UserId"); //adding item to arraylist
ar.add("Directory");
ar.add("Username");
ar.add("PhoneNumber");
// approach one using iteration
for (Iterator<String> it = ar.iterator(); it.hasNext(); ) {
String f = it.next();
if (f.equals("UserId"))
System.out.println("UserId found");
}
// approach two using a colletion which supports fetching element by key
Map<String,String> myMap=new HashMap<>();
for(String strg:ar){
myMap.put(str,str);
}
String result=myMap.get("UserId");
If you have repeating element (for example several "UserId" element), you can use collections that support bags (sets with duplicate elemets), for example guava mutiset

Merging n number of list into a Map based on a value in List

I have the following objects in an ArrayList and a value in this object is illustrated as the numbers at the beginning, which are Id of something.
I need to create a Map object, whose key should be the id of objects and whose values should be the objects with id. At the end of the day, I would like to have a Map something like that.
I have already solved this problem with two for loops and lots of if statements but it seems very ugly to me.
Any cleaner solution would be appreciated.
Map<Integer, List<Foo>> result = list.stream().collect(Collectors.groupingBy(Foo::getId));
Edited to fit the question edit, it is as simple as this:
ArrayList<Element> list = ...;
HashMap<Integer, List<Element>> map = new HashMap<Integer, List<Element>>();
for(Element e : list) {
ArrayList<Element> auxList;
if(map.contains(e.getId()) {
auxList = map.get(e.getId());
} else {
auxList = new ArrayList<Element>();
map.put(e.getId(), auxList);
}
auxList.add(e);
}
Just iterate over the starting list and add the elements to the map. If the map already contains the id, add it to the list. If not, create a new list.

How to create a map of character and dynamic ArrayList in Java

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

How to get the sorted 1D array out of a sorted Hashmap?

I've already made a Hashmap that contains String Keys and Integer values. To be more specific, I collected data from twitter API and i sorted my HashMap in descending order according to the number of followers that every user has.
for example:
#jeremy23 : 13.200 followers
#brandonww :10.343
#aviatoy : 6.002
...
The next thing i want to do is to make an 1dimension array that contains only the names of the users (but keeping the order that the sorting gave me). My goal is to make a ranking array with the most following persons.
My problem is that i get my array back but the names is not in the descending order. Can anyone tell me what the problem may be?
HashMap<String, Integer> rankI = new HashMap<String, Integer>();
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
String user = t.getUser().getScreenName(); // take name of user
int followersCount = t.getUser().getFollowersCount(); // and number of his followers
rankI.put(user, followersCount);
}
//--------------MAKE A SORTED LIST BY VALUES-------------
Comparator<String> comparator = new ValueComparator<String, Integer>(rankI);
TreeMap<String, Integer> result = new TreeMap<String, Integer>(comparator);
result.putAll(rankI);
System.out.println(result);
/--------------Create a sorted array using the map-------
String [] arr1 = new String[rankI.size()];
Set entries = rankI.entrySet();
Iterator entriesIterator = entries.iterator();
int i = 0;
while(entriesIterator.hasNext()){
Map.Entry mapping = (Map.Entry) entriesIterator.next();
arr1[i] = mapping.getKey().toString();
i++;
}
System.out.println(Arrays.toString(arr1));
I am new in StackOverflow and i don't know if it's better to delete the question if i found the mistake, but i guess the right thing to do is to keep the post.
I guess the code is ok. The problem is that in the section " Create a sorted array using the map, i don't use the sorted array whose name is result. I wrongly use the rankI which is not sorted.

Complex Hashmap ArrayList Generator

Here's some code:
ArrayList<String> List = new ArrayList<>();
Map<String, List<String> > map = new HashMap<String, List<String>>();
List.add("stringA");
List.add("stringB");
List.add("stringC");
for(int i = 0; i<List.size();i++){
String key = List.get(i);
List<String> value = new ArrayList<String>();
map.put(key, value);
}
This code takes whatever is in the ArrayList, loops through it, adds it to the Map, and then creates an empty ArrayList with each string name as the variable name. Now, this works, but there's one problem, unless I'm overlooking something. At some point, I will need to access the new empty ArrayLists that are in the map. However, I won't know what the titles of these ArrayLists are, without printing them out, which I don't want to do. Basically, I'm thinking I need a map method or class and then an additional map key method or class. I'm not sure how to implement it but maybe something like this:
public class MapKey {
public MapKey(int count, String header){
}
}
Map<MapKey, List<String> > map = new HashMap<MapKey, List<String>>();
Another option I've considered is to somehow loop through the map array and add Strings to each ArrayList, but I'm very new to maps and looping through them. Especially ones that contain ArrayLists as their values.
There're multiple ways to access keys and values of your HashMap:
for (Map.Entry<String,ArrayList<String>> entry : map.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// do your work
}
or
Set<String> keys = map.keySet();
for(String key : keys){
ArrayList<String> value = map.get(key);
}
Read the java HashMap api Java HashMap Link
Edit:
you dont need to loop through your outside ArrayList objects when you add all of its elements to another, just simply invoke addAll(), it will append all elements of an arraylist to another.
ArrayList<String> aList = map.get("stringA");
assume your first outside ArrayList is called outListOne;
aList.addAll(outListOne);
Appends to corresponding lists:
//assume number of outside lists are equal to number of map elements
String[] keysArr = {"stringA", "stringB", "stringC"};
ArrayList[] outLists = {outListOne, outListTwo, outListThree};
// adds outside lists to corresponding map ArrayList lists
for(int i = 0; i < keysArr.length; i++){
list = map.get(keysArr[i]); // you ArrayList in a map, get it by key name
list.addAll(outLists[i]); // append elements from out list to corresponding list
}
Not exactly sure what you mean by "titles of these ArrayLists." But here are a few code snippets that might give you a better idea of how to work with your map:
// add string x to the list for "stringA"
map.get("stringA").add(x);
// print all the values in the list for "stringC"
for (String s: map.get("stringC")) {
System.out.println(s);
}
// print the names of the lists that contain "xyzzy"
for (String key: map.keySet()) {
if (map.get(key).contains("xyzzy")) {
System.out.println(key);
}
}
// remove "foo" wherever it appears in any of the lists
for (List<String> list: map.values()) {
while (list.remove("foo")){}
}

Categories