I have a hash map of places:
HashMap <String, Integer> places = new HashMap <String, Integer>();
places.put("London",0);
places.put("Paris",0);
places.put("dublin",0);
In this places I have a key of places and a value of how many times that place occurs in a text.
Say I have a texts:
iloveLondon
IamforLondon
allaboutParis
Which are also stored in a hashmap:
HashMap <String, Integer> text = new HashMap <String, Integer>();
I have a conditional statement to check if the place is in the text (where capitals and lower case is ignored:
for (String p: places):
{
for(String t : text):
if t.tolowercase().contains(p.tolowercase())
{
//then i would like to increment the value for places of the places hashmap
}
}
In this example, the output should be:
London, 2
Paris, 1
Dublin, 0
Ive got everything, except outputting the values and incrementing it, any suggestions?
To increment a value all you need to do is:
places.put("London",places.get("London")+1);
If the map does not contain "London" then the get will return a null, to handle that case you need to do:
Integer value = places.get("London");
if (value == null) {
value = 1;
} else {
value += 1;
}
places.put("London", value);
Related
I created a Map<Integer, ArrayList<String>> map and I would like to compare each value in map with one ArrayList<String> likeList and get key if they match. I will bring the key to use later.
I tried to run my code like this, but it doesn't work because it returns nothing:
for (int key : map.keySet()) {
if(map.get(key).equals(likeList)){
index = key;
Log.d("IndexN", String.valueOf(index));
}
}
Then, I tried this:
int index = 0;
for (Map.Entry<Integer, ArrayList<String>> entry : map.entrySet()) {
if(entry.getValue().equals(likeList)){
index = entry.getkey();
}
}
Do you have any idea?
Add a list of the key to store all match
List<Integer> indices = new ArrayList<>();
for (int key : map.keySet()) {
if (map.get(key).equals(likeList)) {
indices.add(key);
}
}
It does not return index when I try the code above.
From this comment, I understood that as soon as you find a match in the map, the index should be recorded and further processing should be stopped. In other words, either there is only one match of likeList in the map or you want to find the first match of likeList in the map. If yes, you need to break the loop as soon as the match is found (shown below).
for (int key : map.keySet()) {
if (map.get(key).equals(likeList)) {
Log.d("IndexN", String.valueOf(index));
break;
}
}
Note that this will give you the same value, each time you execute it, only when the map has only one match of likeList or the map is a LinkedHashMap. If it is a HashMap and it has more than one matches of likeList, you may get a different value each time you execute it because a HashMap does not guarantee the order of its entries.
However, if there can be multiple matches of likeList in the map and you want to log all the matches as well as get the list of the corresponding keys, you can do it as follows:
List<Integer> indexList = new ArrayList<>();
for (int key : map.keySet()) {
if (map.get(key).equals(likeList)) {
Log.d("IndexN", String.valueOf(index));
indexList.add(key);
}
}
// Display the list of corresponding keys
System.out.println(indexList);
Hey guys currently have problem with regards to removing duplicates from hashmap.
Some background:
My hashmap is in this format Map<CompositeKeyBean,ValueBean>.
CompositeKeyBean is in the form (String ID, String hashvalue);
ValueBean is an object.
So if i have a hashmap with values as such:
(ID:1,HashValue:123),Obj1
(ID:1,HashValue:234),Obj1
(ID:1,HashValue:345),Obj1
I need to remove the duplicate keys and only have items with unique IDs. currently I have come up with this, But it does not seem to work, im pretty sure i am doing something wrong.
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
for(int i = 1; i < list.size();i++)
{
if(list.keySet().contains(idvalue))
{
list.remove(i);
}
}
}
My solution for this one would be to declare first an another Map which will be used to hold the number of times that a certain key has appeared in the original Map. For the second time, you can iterate the same map entrySet and remove the duplicates using the declared additional Map as reference.
Map<String, Integer> numberOfInstanceMap = new HashMap<String, Integer>(); //temporary placeholder
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
if(!numberOfInstanceMap.containsKey(idvalue)) {
numberOfInstanceMap.put(idvalue, 1); //initialize the key to 1
} else {
numberOfInstanceMap.replace(idValue, numberOfInstanceMap.get(idValue) + 1); //add 1 to the existing value of the key
}
}
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
Integer i = numberOfInstanceMap.get(idValue);
if(i>1) { //remove duplicate if the key exists more than once
list.remove(idValue);
}
}
If you are expecting duplicate keys, then you can do the following way to handle it while populating the map itself:
Map<String, String> map = new HashMap<>();
if(map.containsKey("ID")){
String oldValue = map.get("ID");
//put logic to merge the value
}else{
map.put("ID","newValue");
}
I have two linked hashmap (key - String, value = String[]) which got the same size and the same keys in both linked hashmaps, I want to be able to compare values according to the key, verifying values on one linked hashmap are equals to the same values in the second linked hashmap (by key) or at least the other linked hashmap contains the values.
I am populating both of the linked hashmaps with keys and values and set it to different linked hash maps.
Example for hashmap:
Key - alert - Value (array of strings)
0 - Device_UID,Instance_UID,Configuration_Set_ID,Alert_UID
1 - a4daeccb-0115-430c-b516-ab7edf314d35,0a7938aa-9a01-437f-88ac-4b2927ed7665,96,61b68069-9de7-4b85-83cb-8d9f558e8ecb
2 - a4daeccb-0115-430c-b516-ab7edf314d35,0a7938aa-9a01-437f-88ac-4b2927ed7665,12,92757faa-bf6b-4aa3-ba6d-2e57b44f333c
3 - a4daeccb-0115-430c-b516-ab7edf314d35,0a7938aa-9a01-437f-88ac-4b2927ed7665,369,779b3294-2ca3-4613-a413-bf8d4aa05d16
and it should be at least in the second linked hash- map
String rdsColumns="";
for(String key : mapServer.keySet()){
String[] value = mapServer.get(key);
String[] item = value[0].split(",");
rdsColumns="";
for(String val:item){
rdsColumns = rdsColumns.concat(val + ",");
}
rdsColumns = rdsColumns.concat(" ");
rdsColumns = rdsColumns.replace(", ", "");
info(("Query is: "+ returnSuitableQueryString(rdsColumns, key, alertId, deviceId)));
String query=returnSuitableQueryString(rdsColumns, key, alertId, deviceId);
mapRDS.put(key, insightSQL.returnResultsAsArray(query ,rdsColumns.split(","),rdsColumns));
}
where rdsColumns are the fields I am querying in RDS data-base.
Expected: iterating over both maps and verifying at that all values according to key in the first map contains or equal in the second map.
This is the code you are looking for:
for (String keys : firstMap.keySet()) {
String[] val1 = firstMap.get(keys);
String[] val2 = secondMap.get(keys);
if (Arrays.equals(val1, val2)) {
//return true;
}
ArrayList<Boolean> contains = new ArrayList<>();
for (int i = 0; i < val1.length; i++) {
for (String[] secondMapVal : secondMap.values()) {
List<String> list = Arrays.asList(secondMapVal);
if (list.contains(val1[i])) {
contains.add(true);
break;
} else contains.add(false);
}
}
if (contains.contains(true)) {
//return true; Even a single value matches up
} else {
//return false; Not even a sinle value matches up
}
}
Basically what we have here is a HashMap<String, String>. We take the set of keys and iterate through them. Then we take the value with the key from the two sets. After we got the values we compare them and if they are the same I just print that they match. You can change this and implement this with other types of HashMaps, even where you use custom values. If I didn't understand your problem tell me and I will edit the answer.
My hashmap class is as follows:
public HashMap<String, Integer> getWordCounts() {
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] quoteOne = getWordArray();
for (String stuff : quoteOne) {
map.put(stuff, +1);
}
return map;
}
As it goes through quoteOne I want it to put each word from the array into the hashmap but for duplicates add 1 to the integer. e.g. "If you see this you are cool" would be put into the hashmap as
if 1
you 2
see 1
this 1
are 1
cool 1
But my code is outting it into the hashmap with you 1. What is wrong?
In your code, for every word you see, you put +1 (the int value of positive 1).
You need to update the value, not override it.
for (String stuff : quoteOne) {
Integer oldVal = map.get(stuff);
if (oldVal == null) {
oldVal = 0;
}
map.put(stuff, oldVal+1);
}
Your for loop will be
for (String stuff : quoteOne) {
if(map.get(stuff) != null){
int i = map.get(stuff);
map.put(stuff,i+1)
}else{
map.put(stuff, 1);
}
}
HashMap replaces values if same key is provided.
From Java doc of HashMap#put
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Try something like this
for(String w : words) {
Integer i = wordCounts.get(w);
if(i == null) wordCounts.put(w, 1);
else wordCounts.put(w, i + 1);
}
for(String i: quoteOne)
map.put(i, (map.get(i)!=null)? map.get(i)+1:1);
I have a List with about 20,000,000 entries. About 5,000,000 entries are unique. I need to iterate over my List, identify unique entries, and assign each an integer between 0 and 5,000,000.
Currently, I sequentially add each entry to a TreeSet, then figure out where it went using .headSet(). I imagine this is suboptimal.
while((nextline = wholefile.listIterator().next()) != null){
//sorted, unique, addition
keywords.add(nextline);
//hmmm, get index of element in TreeSet?
k_j = keywords.headSet(nextline).size();
}
Is there a way to get the location when I call .add() ?
I would simply use a counter and HashMap<Keyword, Integer>. For each keyword in the list, get its position from the map. If you get null, put the keyword in the map with the current counter value as value, and increment the counter.
I would do as follows:
Count the objects by populating a Map<YourObject, Integer>.
Go through this map and assign a sequence number to each key which maps to the value 1.
In code...
List<String> keywords = Arrays.asList("a", "b", "c", "a");
Map<String, Integer> counts = new HashMap<String, Integer>();
for (String str : keywords) {
if (!counts.containsKey(str))
counts.put(str, 0);
counts.put(str, counts.get(str) + 1);
}
int seq = 0;
for (String keyword : counts.keySet())
if (counts.get(keyword) == 1) // is unique?
System.out.println(keyword + " -> " + seq++); // assign id.