I have a weird problem that I don't fully understand how to solve. Could someone please give me some pointers on hashmaps?
I have a variable:
/servlet/charting?base_color=grey&chart_width=288&chart_height=160&chart_type=png&chart_style=manufund_pie&3DSet=true&chart_size=small&leg_on=left&static_xvalues=10.21,12.12,43.12,12.10,&static_labels=blue,red,green,purple"
I basically want 10.21,12.12,43.12,12.10 to be associated with blue,red,green,purple (in the order displayed)
In python I created a method that does this with:
def stripChart(name):
name = str(name)
name = urlparse.urlparse(name)
name = cgi.parse_qs(name.query)
name = dict(zip( name['static_labels'][0].split(','), name['static_xvalues'][0].split(',')))
Not sure how to do this in java. So far I have:
URL imgURL = new URL (imgTag);
String[] result = imgURL.getFile().split("&");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
This gives me:
chart_width=288
chart_height=160
chart_type=png
chart_style=manufund_pie
3DSet=true
chart_size=small
leg_on=left
static_xvalues=10.21,12.12,43.12,12.10,
static_labels=blue,red,green,purple,
At this point I'm confused how to link static_labels and static_xvalues values.
Thanks so much. Any pointers would be awesome.
You want to look at StringTokenizer
Something like this (assuming you stored the labels into the String 'static_labels' and the values in the String 'static_xvalues'):
HashMap<String, Double> colorMap = new HashMap<String, Double>();
StringTokenizer labelTok = new StringTokenizer(static_labels, ",");
StringTokenizer valuesTok = new StringTokenizer(static_xvalues, ",");
while(labelTok.hasMoreElements()){
assert(valuesTok.hasMoreElements());
colorMap.put(labelTok.nextElement(), Double.parseDouble(valuesTok.nextElement()));
}
Look at using java.util.HashMap. Let's say you have stored the static_xvalues and static_labels request parameters into corresponding string variables. Something like the following will create the mapping for you:
String[] vals = static_xvalues.split(",");
String[] labels = static_labels.split(",");
HashMap<String,String> map = new HashMap<String,String>();
for (int i=0; i < vals.length; ++i) {
map.put(labels[i], values[i]);
}
You do not say if the xvalues need to be stored as floats or not. If so, you will need to convert the vals array into a Float (or Double) array first, and modify the HashMap instantiation accordingly:
HashMap<String,Float> = new HashMap<String,Float>();
Related
Sorry for my bad English. I am using two separate string array for each item of arraylist. All things working fine . My Question is I want to take each item of String array (say) if i take string array "asasaqty" and another item of string array "asasaId" then I want to store each item of string array value in third string array (say:[id1,qty1] and so on). Please let me know if there is a proper solution for this.
Below is my code.
Thanks in advance
String [] asasaqty;
String [] asasaId;
final AddToCartData addToCartData = response.body();
shoppingBagArrayList = addToCartData.getData();
asasaqty = new String[shoppingBagArrayList.size()];
asasaId = new String[shoppingBagArrayList.size()];
for (int i = 0; i < shoppingBagArrayList.size(); i++) {
asasaqty[i] = shoppingBagArrayList.get(i).getQty();
asasaId[i]=shoppingBagArrayList.get(i).getProductId();
System.out.println("==========wwwww========"+ Arrays.toString(asasaqty));
System.out.println("======wwwwssssswwwwss======"+ Arrays.toString(asasaId));
/* HashMap<String,String> map=new HashMap<String,String>();
for (int i = 0; i < asasaqty.length; i++) {
map.put(asasaqty[i],asasaId[i]);
System.out.println("======aaaaaaa======"+ map.put(asasaqty[i],asasaId[i]));
}*/
After printing the value in logcat the value is looking like
/System.out: ==========wwwww========[3, 2]
/System.out: ======wwwwssssswwwwss======[151, 10]
Now i want to take another String array and store each item asasaqty and asasaId in separate array like below
String[] xyz = [3,151] and
String[] abc = [2,10]
Please let me know how can we do this.
You can use productID and key (Assuming it is unique) and qty as value.
HashMap<Integer,Integer> dataMap = new HashMap<>();
for (int i=0; i <shoppingBagArrayList.size; i++){
dataMap.put(shoppingBagArrayList.get(i).getProductId() , shoppingBagArrayList.get(i).getQty());
}
System.out.println("DataMap: "+dataMap);
I have a dataset of doubles in form of JavaRDD. I want to remove the rows(vector) containing null values. I was going to use filter function in order to do that but cannot figure out how to to do it. I am pretty new to spark and mllib and would really appreciate it if you could help me out.This is how my parsed data looks like:
String path = "data.txt";
JavaRDD<String> data = sc.textFile(path);
JavaRDD<Vector> parsedData = data.map(
new Function<String, Vector>() {
public Vector call(String s) {
String[] sarray = s.split(" ");
double[] values = new double[sarray.length];
for (int i = 0; i < sarray.length; i++)
values[i] = Double.parseDouble(sarray[i]);
return Vectors.dense(values);
}
}
);
Checking a vector[i] element against null might put you in the clear?
And then perform an operation similar to vector.remove(n). Where "n" is the element to be removed from the vector.
Vector values = Vectors.dense(new double[vector_length]);
parsedData = parsedData.filter((Vector s) -> {
return !s.equals(Vectors.dense(new double[vector_length]));
});
As mentioned in the comments, RDD vector can't be NULL. However, you might want to get red of empty (Zero) vectors utilizing the filter method. This can be done by creating an empty vector and filtering it out.
I'm relatively new to Java and trying to create an application to help with my trading. I have a method to read a csv file that I input, which is table with x number of rows and 3 columns. It reads it as multidimensional String array (String[][]) Eg
Pair----- Buy Price ---Sell Price
AUDUSD 0.9550 --- 0.9386
EURUSD 1.3333 --- 1.3050
GBPUSD 1.5705 --- 1.5550
(please excuse my formatting)
I have a constructor called ForexPair that looks like this:
public class ForexPair extends PriceWarning{
public String pairName;
public double buyPrice;
public double sellPrice;
public ForexPair(String pair, String buy, String sell) {
pairName = pair;
buyPrice = Double.valueOf(buy);
sellPrice = Double.valueOf(sell);
}
My question is this: Can I use a 'for' loop to create an object for each row in my CSV file? I believe I can use an ArrayList for this. However I want the name of each object I create to be the Pair Name in the first column of my csv file. For example:
ForexPair AUDUSD = new ForexPair(pairNames[0], (myArray[0][1]),(myArray[0][2]));
But how do I create the object called AUDUSD using a for loop? So that each object has a different name?
Currently I have this code:
public static void main(String[] args) {
String[][] myArray = getInputArray();
String[] pairNames = new String[myArray.length];
for(int i = 0; i < pairNames.length; i++){
pairNames[i] = myArray[i][0]; //Creates 1D String array with pair names.
ForexPair pairNames[i] = new ForexPair(pairNames[i], (myArray[i][1]),(myArray[i][2]));
}
}
Variable names are not relevant - they aren't even kept track of after your code is compiled. If you want to map names to objects you can instead place ForexPair instances in a Map<String, ForexPair>, i.e.
Map<String, ForexPair> map = new HashMap<String, ForexPair>();
...
// in the for-loop:
map.put(pairNames[i], new ForexPair(pairNames[i], myArray[i][1],myArray[i][2]));
Although this seems slightly redundant, as you already have the name as a field in each ForexPair, so you might want to consider removing this field and keeping track of the name only via the map.
Yes you can. Use a HashMap.
rough example:
HashMap<String, ForexPair> myMap = new HashMap<String, ForexPair>();
myMap.put("AUDUSD", new ForexPair(pairNames[0], (myArray[0][1]),(myArray[0][2])));
ForexPair pair = myMap.get("AUDUSD");
1.
Can I use a 'for' loop to create an object for each row in my CSV file?
Yes, that's possible:
BufferedReader br = new BufferedReader(new FileReader(yourCsvFile));
String line;
while((line = br.readLine()) != null) {
// do something with line.
}
2.
But how do I create the object called AUDUSD using a for loop? So that each object has a different name?
I think your mixing up two different concepts: name of variable and value of your variable called pair
The value of your variable is the important point, while the name of your variable only provides code quality!
final TableLayout tview = (TableLayout) findViewById(R.id.tblGridStructure);
final JSONArray JarraymenuItems = {item1,it3m1mwer,wer,ds};//your list of items
for (int i = 0; i < JarraymenuItems.length(); i++)
{
ableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tview.addView(tr, LayoutParams.FILL_PARENT, 45);
T
final TextView etprice = new TextView(this);
etprice.setText("your text value wat u want to display");
tr.addView(etprice );
int count = tview.getChildCount();
if (count % 2 != 0)
tr.setBackgroundColor(Color.parseColor("#E3E3E3"));
}
I am trying to create an application which retrieves the users favourite book quote however I am stuck on how to display this information back to the user. I created an ArrayList which will store all the information. However when displaying this information, I keep getting the error:
java.lang.NullPointerException
when it tries to execute the code
temp[i] = new HashMap<String,String>();
This class is shown below:
public class FavouriteQuotesActivity extends ListActivity {
static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
private void getFavorites() {
DataBaseHelper myDbHelper = new DataBaseHelper(this);
String favorites [] = myDbHelper.getFavourites();
if(list.size() > 0)
{
list.removeAll(list);
}
for(int i = 0;i < favorites.length; i++)
{
String quotes = favorites[i];
String[] quoteArray = quotes.split(":");
HashMap<String,String> temp[] = null;
temp[i] = new HashMap<String,String>();
temp[i].put("Author",(quoteArray[2]));
temp[i].put("Quote",(quoteArray[4]));
list.add(temp[i]);
}
}
Any help would be greatly appreciated.
Look at this code:
HashMap<String,String> temp[] = null;
temp[i] = new HashMap<String,String>();
You've just assigned a null value to the temp variable (which would more typically have a declaration of HashMap<String, String>[] temp) - so of course you'll get a NullPointerException when you then try to access temp[i] on the very next statement.
It's not clear why you're using an array at all in that code - why aren't you just using:
HashMap<String, String> map = new HashMap<String, String>();
map.put("Author", quoteArray[2]);
map.put("Quote", quoteArray[4]);
list.add(map);
Additionally it's unclear why you're using a map at all here, given that it will always have the same two keys. Why not create a Quote class with name and author properties? Also, using a static variable here seems like a bad idea - why doesn't getFavorites create a new list on each invocation, and return it at the end of the method?
You are declaring and using temp wrong. You don't need an array of HashMap, just a single HashMap, since list is an ArrayList<HashMap>:
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("Author",(quoteArray[2]));
temp.put("Quote",(quoteArray[4]));
list.add(temp);
temp doesn't point to an array. You are setting it to null.
You declared the variable temp as an array (by writing HashMap temp[]).
Without being it an actual array, you can't set any elements.
I have the following
String[] temp;
which returns
red
blue
green
I would like to add the string array into a collection obejct like HashMap so that I could retrieve values in any class like
HashMap hash = New HashMap();
hash.get("red");
hash.get("blue");
hash.get("green");
How can I do this?
Thanks
Update 1
String str = "red,blue,green";
String[] temp;
String delimiter = ",";
temp = str.split(delimiter);
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
With the above code, I would like to retrieve values based on values in array. E.g. I would like to get the values in from another class by calling hash.get("One"), which would return red, hash.get("Two") which would return blue and so forth.
Map<String, String> hash = new HashMap<String, String>();
for(i = 0 ; i < temp.length(); i++)
{
hash.put(temp[i], temp[i]);
}
Then you can retrieve from map
hash.get (temp[i]);
HashMap<String, String>() map = new HashMap<String, String>();
map.put(temp[i], temp[i]);//here i have considered key as the value itself.. u can use something else //also.
My doubt how I do map temp[i] with red, blue or green?
Using a hash map won't solve this problem directly. Currently you need to write
temp[ someNumberHere ];
so
temp[ 1 ];
yields a String "blue"
If you have a hashMap then instead you might write
myColourMap.get( someNumberHere );
so
myColourMap.get( 1 );
Would yield "blue". In either case you are converting a value to a corresponding string, but you do need to know that "someNumber". If you want "blue" you need to know to ask for number 1.
It may be that what you need is to use nicely named constant values:
public Class Colours {
public static final int RED = 0;
public static final int BLUE = 1;
public static final int GREEN = 1;
// plus either the array of strings or the hashMap
public statuc String getColour(int colourNumber ) {
return myArray[colourNumber]; // or myMap.get(colourNumber)
}
}
Your clients can now write code such as
Colours.getColour( Colour.RED );
[It is better to use enums than just raw ints, but let's not divert from arrays and hashMaps right now].
Now when might you prefer a hashMap instead of an array? Consider that you might have more colours, for example 12695295 might be "light pink" and 16443110 might be "lavender".
Now you really don't want an array with 16,443,110 entries when you are only using perhaps 500 of them. Now a HashMap is a really useful thing
myMap.put( Colour.LAVENDER, 16443110 );
and so on.