Adding values in to a HashMap - java

I need help to add the values from a String array into a HashMap.
if (!loaded){
synchronized(syncLock){
if (!loaded){
loaded=true;
if (prefix!=null){
prefixMap = new HashMap<Integer, Float>();
String userDefaultPrefix[] = prefix.split("~");
}
}
}
}
I have the strings stored in userDefaultPrefix, and i need to add those values into prefixMap. TIA

If I get you right and you're sure in data quality than you can fill prefixMap following way:
for (int i = 0; i < userDefaultPrefix.length; i += 2) {
if (i+1 < userDefaultPrefix.length) {
prefixMap.put(Integer.parseInt(userDefaultPrefix[i]),
Float.parseFloat(userDefaultPrefix[i+1]));
}
}

assuming you want a map of (i->userDefaultPrefix[i]):
for (int i = 0; i < userDefaultPrefix.length;i++) {
prefixMap.put(i,userDefaultPrefix[i]); //note that the autoboxing automatically boxes your int to an Integer
}

Related

ArrayList - Count if the same Object i listed exact 2 times and if: append to "tempFinalFilterSearchList"

Basicly im trying to look through an Arraylist to check if the same object is listed 2 times - and if: append to "tempFinalFilterSearchList"
Im not allowed to use Hashmap (School assignment).
UPDATE - This code actual works now... Now I just need to remove dublicates from "tempFinalFilterSearchList"
public List<Venue> filterToFinalSearchList()
{
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int occurences=0;
for (int j = 0; j < tempFilterSearchList.size(); j++)
{
if (tempFilterSearchList.get(i).getVenueId() == tempFilterSearchList.get(j).getVenueId())
{
occurences++;
}
}
if (occurences == 2)
{
tempFinalFilterSearchList.add(tempFilterSearchList.get(i));
}
}
return tempFinalFilterSearchList;
}
if the same venueId is listed exact 2 times in "tempfilterSearchList", then the Object have to be added to "tempFinalFilterSearchList"...
have tried several different things now, without luck - And also search here / google - there alot of solutions, but all with Hashmap which im not allowed to use.
Thank you in advance for any advise.
First of all keep in mind that using the remove function inside a loop for the same list is not safe(Unless using an iterator).
I assume you have a class let's call it A that has the attribute venueId.
It looks something like this + other attributes that you want:
public class A {
private int venueId;
public A(int venueId) {
this.venueId = venueId;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
}
1.Create a function that parses the list and counts the number of times an object with the same venueId repeats itself
public boolean doesVenueIdRepeatInList(int venueId, List<A> list) {
int timesRepeated = 0;
//Parse the list and count the number of items that have the same venueId
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getVenueId() == venueId) {
timesRepeated++;
}
}
//If the venueId repeats more than 3 times
if (timesRepeated >= 3) {
return true;
}
return false;
}
3.Now to the code that actually does what you asked.
We will parse the list and identify the the objects that repeat more than 3 times.
If they repeat more than 3 times we won't add them to the new list
List<A> tempFilterSearchList = Arrays.asList(
new A(1),
new A(2),
new A(1),
new A(2),
new A(3),
new A(1),
new A(2)
);
//We will be using a new list to put the result in
//It's not safe to use the delete function inside a loop
List<A> filteredList = new ArrayList<>();
//Count the number an object repeats and if it repeats more than 3 times store it inside repeatedVenueIds
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int venueId = tempFilterSearchList.get(i).getVenueId();
boolean itRepeat3Times = doesVenueIdRepeatInList(venueId, tempFilterSearchList);
//If it doesn't repeat more than 3 times add it to the new list
if(!itRepeat3Times) {
filteredList.add(tempFilterSearchList.get(i));
}
}
You have your result inside filteredList
It is a better advanced option to use 'iterator' since it allows you to remove elements while iterating an arraylist
ArrayList<Integer> tempFilterSearchList = new ArrayList<Integer>(Arrays.asList(1,2,5,3,7,3,7,3) );
Iterator itr = tempFilterSearchList.iterator();
while (itr.hasNext())
{
int count = 0;
int number = (Integer)itr.next();
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int x = tempFilterSearchList.get(i);
if (x == number)
{
count++;
}
}
if( count != 3 )
{
itr.remove();
}
}
"using the remove function inside a loop for the same list is not safe. " this will not be an issue if you use iterator in java which is a advance option in java language
Your code must look like the folowing. First of all you should loop over all the elements in tempFilterSearchList. Then for each element, you should count the number of times it appears in the list. I choosed rather to place all the positions where the current elements' venueId occures in separate List to further delete them easly.
ArrayList<Integer> occurrences = new ArrayList<Integer>()
for (int i=0; i < tempFilterSearchList.size(); i++)
for (int j=0; j < tempFilterSearchList.size(); j++){
if(tempFilterSearchList.get(i).getVenueId() ==tempFilterSearchList.get(j).getVenueId()){
occurrences.add(j)
}
}
if(occurrences.size() != 3){
for(int j:occurrences){
tempFilterSearchList.remove(occurrences[j])
}
}
}

How to add repeated data in Java array?

I am having an array with name (String name[]={"a","b","a","c","a","b","c"};) and another array with quantity (int qty[]={10,20,10,40,10,40,70};) corresponding with name array. Now, i just want another array having addition of similar qty[] values corresponding to their name[] i.e. i need tempname[]={"a","b","c"} and tempqty[]={30,60,110}. here tempname contains unique values from name and tempqty contains addition of a,b,c.
temp=name;
qty1=qty;
for(i=0;i<name.length;i++){
temp1=qty[i];
for(int j=0;j<name.length;j++){
if (name[i]==temp[j+1]){
temp1=temp1+qty1[j+1];
}
}
}
I tried above method. Here, i am able to get addition of qty of "a" name but i am not getting my result. please suggest me on this or give me any another way to solve the problem. thank you in advance.
You can do this easily by ArrayList. I did this for you:
String name[]={"a","b","a","c","a","b","c"};
int qty[]={10,20,10,40,10,40,70};
ArrayList<String>tempname= new ArrayList<String>();
ArrayList<Integer>tempqty= new ArrayList<Integer>();
for(int i=0;i<name.length;i++){
int index=tempname.indexOf(name[i]);
if(index==-1){
tempname.add(name[i]);
tempqty.add(qty[i]);
}
else{
tempqty.set(index,tempqty.get(index)+qty[i]);
}
}
for(int i=0;i<tempname.size();i++){
System.out.printf(tempname.get(i)+" ");
}
System.out.println();
for(int i=0;i<tempqty.size();i++){
System.out.printf(tempqty.get(i)+" ");
}
Use a HashMap:
HashMap<String, Integer> quantity = new HashMap<>();
for(int i = 0; i < name.length; i++) {
if(!quantity.containsKey(name[i])) {
quantity.put(name[i], qty[i]);
} else {
quantity.put(name[i], quantity.get(name[i]) + qty[i]);
}
}
Untested, but you'll get the idea.
I suggest to use something like hashmaps for this
Example:
HashMap<String, int> hmap = new HashMap<String, int>();
hmap.put("a", 1);
hmap.put("b", 2);
To get a value use
hmap.get("a"); // will give 1
To loop through everything
Iterator it= hmap.keySet().iterator();
while(it.hasNext()) {
String key=(String)it.next();
int value=(int)hmap.get(key);
// do something
}
If you want to put values together because they belong together you could create a class.
class MyStoreThing {
String name;
int quantity;
}
int getSummarizedQuantityOfAllWithName(String name) {
int summarizedQuantity = 0;
for (int i = 0; i < myList.length; i++) {
summarizedQuantity += name.equals(myList.getName()) ? myList.getQuantity : 0;
}
return summarizedQuantity;
}
ArrayList<MyStoreThing> myList = new...;
// populate list: myList.add(new MyStoreThing("a", 10)) ...
// call getSummarizedQuantityOfAllWithName("a");

Comparing Elements in the same ArrayLists and add to Hashmap

I got a quick question.
Currently, I have a userList (of String) and timeLime (of Integer).
These values were added in order and therefore each .get(i) will contain the user (userList) with his time (timeList).
As there may be duplicate instances of users in the name ArrayList, I would like to sum up the total time for each user in timeList and put it to a hashmap of <String, Integer>, but I do not know how to do it.
Currently, what I have done is:
for (int i = 0; i < userList.size(); i++) {
count = 0;
for (int j = 0; j <userList.size(); j++) {
if (!userList.get(i).equals(userList.get(j))) {
count++;
}
}
if (count == userList.size() -1) {
System.out.println("Adding in " + userList.get(i));
map.put(userList.get(i), timeList.get(i));
}
}
I am stuck till the point where if there is a match. I do not know how to add the time together and put it in the hashmap.
I'm not very proficient in Java and would like some help. Thanks in advance.
Do you want to create one HashMap with user and the sum of time that may appear anywhere in the two lists? If that is the case, the following code will do it for you.
List<String> userList = new ArrayList<String>(Arrays.asList("ann", "john", "tim", "ann"));
List<Integer> timeList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 5));
Map<String, Integer> userTimeMap = new HashMap<String, Integer>();
for (int i = 0; i < userList.size(); i++) {
String user = userList.get(i);
Integer time = userTimeMap.get(user);
if (time == null) {
userTimeMap.put(user, timeList.get(i));
} else {
userTimeMap.put(user, time + timeList.get(i));
}
}
Result : {john=2, ann=6, tim=3}
I would do it in this way:
for (int i = 0; i < userList.size(); i++) {
// check whether the entry is already there
if (map.containsKey(userList.get(i))){
// If already exists add
map.put(userList.get(i), map.get(userList) + timeList.get(i));
}else{
// else make a new entry
map.put(userList.get(i), timeList.get(i));
}
}

Java count occurrence of each item in an sorted array

I have an Array of Strings and want to count the occurrences of any single String.
I have already sorted it. (It's a long Array and I wanted to get rid of the O(n²)-loop)
Here my code.. obviously it runs out in an ind.outOfB. exc.. the reason is clear but I donno how to solve..
for (int i = 0; i < patternsTest.length-1; i++) {
int occ=1;
String temp=patternsTest[i];
while(temp.equals(patternsTest[i+1])){
i++;
occ++;
}
}
This would be a good place for a HashMap, the key would be the Word, and the value the Number of times it occurs. The Map.containsKey and Map.get methods are constant time lookups which are very fast.
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i = 0; i < patternsTest.length; i++) {
String word=patternsTest[i];
if (!map.containsKey(word)){
map.put(word,1);
} else {
map.put(word, map.get(word) +1);
}
}
As a side benefit you don't even need to sort beforehand!
You can use Java HashMap:
Map<String, Integer> occurrenceOfStrings = new HashMap<String, Integer>();
for(String str: patternsTest)
{
Integer currentValue = occurrenceOfStrings.get(str);
if(currentValue == null)
occurrenceOfStrings.put(str, 1);
else
occurrenceOfStrings.put(str, currentValue + 1);
}
This does not have index out of bounds:
String[] patternsTest = {"a", "b"};
for (int i = 0; i < patternsTest.length-1; i++) {
int occ=1;
String temp=patternsTest[i];
while(temp.equals(patternsTest[i+1])){
i++;
occ++;
}
}
You can cause an Index Out of Bounds by changing the data to:
String[] patternsTest = {"a", "a"};
you could try a map and only one loop
Map<String, Integer> occurences = new HashMap<String, Integer>();
String currentString = patternsTest[0];
Integer count = 1;
for (int i = 1; i < patternsTest.length; i++) {
if(currentString.equals(patternsTest[i]) {
count++;
} else {
occurrences.put(currentString, count);
currentString = patternsTest[i];
count = 1;
}
}
occurrences.put(currentString, count);
Guava Multiset solution (two lines of code):
Multiset<String> multiset = HashMultiset.create();
multiset.addAll(Arrays.asList(patternsTest));
//Then you could do...
multiset.count("hello");//Return count the number of occurrences of "hello".
We could use it both sorted and un-sorted arrays. Easy to maintain code.
My solution is:
public int cantOccurences(String pattern, String[] values){
int count = 0;
for (String s : values) {
count += (s.replaceAll("[^".concat(pattern).concat("]"), "").length());
}
return count;
}

issue with sort data

i am developing an app in which i get data from server and display in map. but before display it on map's balloon i have just sort data by one field name is "Destination" and there are method made na,e is ..GOTOSORT....
now problem is i got variables s with length 1 and there for the for loop are run only 1 time , but there are 42 data are come from webservices so please check it and tell me what is the problem
private void GOTOSORT() {
Log.i(TAG, " SORT ");
Map<Float, Integer> map = new TreeMap<Float, Integer>();
for (int i = 0; i < lng_timeStamp.length; ++i) {
map.put((float) lng_timeStamp[i], i);
}
Collection<Integer> indices = map.values();
System.out.println("indices" + indices);
Integer s[] = (Integer[]) indices.toArray(new Integer[0]);
Log.i(TAG, "s.length"+s.length);
for (int i = 0, n = s.length; i < n; i++) {
System.out.println(s[i]);
int_sort_MyhourGetTime[i] = int_MyhourGetTime[s[i]];
int_sort_MyMinGetTime[i] = int_MyMinGetTime[s[i]];
lng_sor_timeStamp[i] = lng_timeStamp[s[i]];
arr_sort_ServiceNumber[i] = arr_ServiceNumber[s[i]];
arr_sort_Destination[i] = arr_Destination[s[i]];
}
If you want to sort your list , you should follow the Java's comparatorFollow here
It will return you a sorted list in any order.
All the best !! :)

Categories

Resources