return dictionary using hashmap java - java

I am very new to java had a question regarding returning the dictionary with the help of hashmap. The problem is I have string array let say with four names and I have to iterate and differentiate name according to the string length and if the key does not match I have to create other list and if it matches I have to simply append the string.
Basically the expected output should be like this
3:kel
4:john,aron
5:sonny
6:abraham
I tried little bit but stuck code looks like this
public static void main(String arg[])
{
HashMap<integer, ArrayList<String>> map = new HashMap<integer, ArrayList<String>>();
ArrayList<String> namelist = new ArrayList<String>();
obj.add("john");
obj.add("kel");
obj.add("abraham");
obj.add("sonny");
obj.add("aron");
map.put(3, namelist);
for (int i = 0; i < namelist.size(); i++) {
String element = namelist[i];
String nextElement = elements[i+1];
}
}

Your datatypes on the HashMap are not ideal. You want HasMap<Integer, List<String>>, although you could use String as a key if you call toString on the integer length of the name before using it as a key. Then, loop through the obj list and check if the length of the string you're on (obj[i].length()) exists in map using map.containsKey(obj[i].length()). If it does exist, you will map.get(obj[i].length()).add(obj[i]), and if it doesn't you will create a new ArrayList containing obj[i] and use the .put method on the HashMap to add it.
In the code you posted, first appears to not be defined.
I would rename obj to nameList, or something more descriptive. It's not an object.

Java 8's streaming capabilities offer a pretty elegant one-liner for this with the built in groupingBy collector:
Map<Integer, List<String>> map =
obj.stream().collect(Collectors.groupingBy(String::length));

Related

How to access a single ArrayList in ArrayListMultiMap

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")){...}

How to use collection in Java

I want to use Java collection to find the words in the list that begin with the startup letter:
example:
TreeMap<String, Double> tm = new TreeMap<String, Double>();
// Put elements to the map
tm.put("Zara", new Double(3434.34));
tm.put("Mahnaz", new Double(123.22));
tm.put("Ayan", new Double(1378.00));
tm.put("Daisy", new Double(99.22));
tm.put("Qadir", new Double(-19.08));
Toast.makeText(getApplicationContext(), ""+tm.get("Zar"),Toast.LENGTH_SHORT).show();
in this case it will show null. But what i want to do is to show all the words that start with that letter. How can i do this? Thanks in advance
Since TreeMap is a NavigableMap, it is computationally cheap to iterate the map starting from a given key:
String prefix = "Zar";
for (String person::tm.tailMap(prefix).keySet()) {
if (person.startsWith(prefix)) {...}
}
There are a few choices:
If you always go from the first three characters then do a multimap - Map<String, List<Data>> Where Data contains String name and double double and the key is the first three letters of all the names.
You can scan through the TreeMap and because it is sorted at least you know you can stop once you get past Zar - but this will still be inefficient.
You can use a database (embed a Derby Database for example) and use the indexing/search/query functionality of the database.
You can build your own tree structure branching on each character in the word. Then root->z->a->r would then give you every word beginning with zar. root->b->o would give you every word beginning with bo, etc.
TreeMap<String, Double> tm = new TreeMap<String, Double>();
//...add values.
//get all keys
Set<String> keys = tm.keySet();
Set<String> result = new HashSet<String>();
for(String key : keys){
//check the beginning of the keys
if(key.startsWith("Zar"){
result.put(key);
}
}
//get the values for your collected keys
for(String key : result){
double value = tm.get(key);
}
Just reading when to use what collection will only help you if you run across the exact same situation in your code. If you don't understand the roots of why a given data structure is good for a problem, you won't be able to apply this to your own code.
this link may help you
You only have to Iterate over the list and check if the key starts with the given String.
Example:
for (String elem : tm.keySet()) {
if(elem.startsWith("Zar")) {
System.out.println(elem);
}
}
output:
Zara
and if you want to ignore the case:
if(elem.toLowerCase().startsWith("zar".toLowerCase()))
So How can you achieve this?
First find all the keys of HashMap by
tm.keySet()
then use iterator on keys and match with the string.See example below
String abc = "Zar";
HashMap s = new HashMap();
s.put("Zara", new Double(1.0));
Set x =s.keySet();
Iterator iter = x.iterator();
while (iter.hasNext()) {
String key = iter.next().toString();
if(key.startsWith(abc)){
System.out.println(s.get(key));
}
}

ArrayList in HashMap using a method in Java

I have a HashMap with ArrayList as values:
HashMap <String, ArrayList<String>> Test
ArrayList<String> fruit = new ArrayList<>();
fruit.add("bananas");
fruit.add("apples");
Test.put("fruit", fruit);
ArrayList<String> cities = new ArrayList<>();
cities.add("London");
cities.add("Paris");
Test.put("cities", cities);
I want to access the first element of each ArrayList, but using a method. For example something like that:
public String getSomething (ArrayList<String> Something) {
return (Test.get(Something)).get(1);
}
But this is not working as 'Something' must be an ArrayList. Any ideas about that? Is there another way of accessing a HashMap with multiple values for one key?
If you look at the Javadoc , you can see that HashMap has a method called values()
So you can retrieve the values and you just need to iterate on it.
Edit: The Java arrays and lists starting index is 0.
The method you have accepts an ArrayList arg but you are trying to pass the HashMap. Maybe you want something like this:
public String getSomething (HashMap<String, ArrayList<String>> map, String key, int n) {
ArrayList<String> something = (ArrayList<String>)map.get(key);
return something.get(n);
}

Add string representation of a LinkedHashMap<String,String>

I have a String that has been constructed from another LinkedHashMap using toString method, and I want to do the reverse in creating another LinkedHashMap<String, String> with this String representation of the previous LinkedHashMap.
Is it possible withing using String splits and manually doing it in a loop calling LinkedHashMap.put() ?
I think this could work?
LinkedHashMap params = new LinkedHashMap();
String[] split = paramsString2.split(",");
for (int i = 0; i < split.length; i++) {
String[] nameValue = split[i].split("=");
params.put(nameValue[0], nameValue[1]);
}
return params;
Assume the string is of the form
key1=value1;key2=value2;key3=value3
Yes, it is possible. Use string.split(";") to separate the map entries into an array.
Then loop through the array, and for each entry, use string.split("=") to separate the key from the value.
Then add the key and value to the new LinkedHashMap:
String[] parts = entry.split("=");
map.put(parts[0], parts[1]); //parts[0] is the key, parts[1] is the value
Sure it is possible, but why should you do such horrible stuff?
Anyway, yes it is possible, you could also use the guava library to accomplish such a job.
guava-library

Java, How to add values to Array List used as value in HashMap

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

Categories