I have a method return type as ArrayList<String> which is also reading an argument of the same type. Now how do I type cast or modify my BigDecimal to read that value?
public static ArrayList<String> currencyUtilArray(ArrayList<String> amountStr ) {
BigDecimal amount = new BigDecimal(ArrayList<String> amountStr);
//How do I define that the amountStr is ArrayList<String> and need to place in BigDecimal amount one after another till the end of the List
return amountStr;
}
Or do I need to do
You can't type cast a String to a BigDecimal or vice versa.
If the strings in the array are meant to represent a number when concatenated then do something like this:
StringBuilder sb = new StringBuilder();
for (String s : amountStr) {
sb.append(s);
}
BigDecimal amount = new BigDecimal(sb.toString());
On the other hand, if each String represents a distinct number:
for (String s : amountStr) {
BigDecimal amount = new BigDecimal(s);
// ... and do something with it ...
}
I don't think you are referencing it correctly. You can't convert the whole ArrayList as an AL of type string to a Big Decimal.
First, change the ArrayList amountStr from within the new BigDecimal(--); and reference a single String from within the ArrayList.
Meaning you would have to loop through the whole thing, adding it into amount:
BigDecimal amount = new BigDecimal(amountStr.get(0));
For(int i = 1; i < amountStr.size(); i++){
amount = amount.add(new BigDecimal(amountStr.get(i)));
}
I believe that should give you what you need when it is returned.
what i understand is you want to convert the list elements into BigDecimal Array. If so you can do as below:
BigDecimal[] amount = new BigDecimal[amountStr.size()];
for (int i=0;i<amountStr.size();i++) {
amount[i] = new BigDecimal(amountStr.get(i));
}
Related
How would I iterate through an array and attempt to convert a string to a long? This is an example below:
String[] myArray = ["123", "122 Street", "2334"];
// I'm trying to loop through an array like this and cast to a long
for(String s: myArray) {
try {
long newValue = Long.valueOf(s);
// How would I swap the old values to their new long type in the
// myArray?
} catch(Exception error) { }
}
You cannot put a long into a String[]. You'd need to create a second array specifically for holding the longs. I'm unsure whether "122 Street" would cast correctly or give an error.
String[] myArray = ["123", "122 Street", "2334"];
long[] longs = new long[myArray.length];
for (int i = 0; i < myArray.length; i++) {
try {
longs[i] = Long.valueOf(myArray[i]);
} catch (Exception e) {
// Handle error case
}
}
Java arrays only store the type they were declared to store (Java ain't JavaScript).
Here's a 1-liner:
long[] numbers = Arrays.stream(myArray)
.filter(s -> s.matches("\\d+"))
.mapToLong(Long::parseLong)
.toArray();
before converting a string to long, I'd validate that it has only digits in order to avoid exceptions which are very costly in Java (unlike other languages such as Python in which raising and catching exceptions is perfectly normal).
Since we have no way of knowing what will be the size of the new array, and having array that contains nulls is not ideal, we can work with a List to collect the results and when we're done - convert it into an array of Long
public static void main(String[] args) {
String[] myArray = {"123", "122 Street", "2334"};
Long[] array = stringsToLongs(myArray);
}
private static Long[] stringsToLongs(String[] myArray) {
List<Long> list = new LinkedList<>();
for(String s: myArray) {
if (s.matches("\\d+"))
list.add(Long.valueOf(s));
}
return list.toArray(new Long[list.size()]);
}
How would I swap the old values to their new long type in the myArray?
You wouldn't. Your array is already of Type of string. It can only accept string values. If you want an equivalent array of type long, you will need exactly that. A different array, of that type; with equivalent values stored inside.
Other answers are not technically correct in their current wording. One can put a long value in a string[] array; just not in a long type/format.
The same applies in reverse (which is what you seem to want to do): You can have long[] holding data that was previously in string type/format. You just need to do the proper conversion.
Another thing other answers get slightly wrong, is that there is technically no casting, in the true meaning of the word, between numerical types and strings. What is done instead is called parsing.
In the case of your issue specifically, parsing a long value from it's string representation is done using long.valueOf(string s).
Note that this method expects a string representation of a number, and will fail with NumberFormatException with something else.
This includes "122 Street". That's not a number. "122" is. So you'll have to parse "122" out of the rest of the string first, before converting that to long.
Solution:
String[] myArray = ["123", "122 Street", "2334"];
myArray[1] = myArray[1].substring(0,2); //Removes " Street" from second element.
long[] myLongs = new long[myArray.length];
for(int i=0; i<myArray.length; i++) {
try {
myLongs[i] = Long.valueOf(myArray[i]);
} catch(NumberFormatException nfe) {
System.out.println("Element at index "+i+" could not be parsed.");
} catch(Exception ex) {
System.out.println("Some other exception happened.");
}
}
Sorry if the title is not clear, I'm not very good with programming jargon.
I have 2 string ArrayLists and an integer ArrayList obtained from one method which is passed to a separate method through the collection LinkedHashMap< String, List< String>>. However, when I try to set the integer ArrayList into a empty ArrayList declared in the receiving method, it shows the syntax error: "incompatible types: List< String> cannot be converted to List< Integer>".
Starter Method:
public static void main(String[] args) {
try{
LinkedHashMap lhm = new LinkedHashMap();
List<String> listEPC = new ArrayList<String>();
List<String> listTimeStamp = new ArrayList<String>();
List<Integer> listAntenna = new ArrayList<Integer>();
String tagID = "EQ5237";
String TimeStampStr = "12:23:22";
int tagAntenna = 2;
listEPC.add(tagID);
listTimeStamp.add(TimeStampStr);
listAntenna.add(tagAntenna);
lhm.put("epcs", listEPC);
lhm.put("timestamps", listTimeStamp);
lhm.put("antennas", listAntenna);
insertData insert = new insertData();
insert.insertData(lhm); //send map with values to new method
}catch(Exception e){
e.printStackTrace();
}
}
Receiving Method:
public class insertData {
public void insertData(LinkedHashMap<String, List<String>> readMap) {
List<String> listEPC = new ArrayList<String>();
List<String> listTimeStamp = new ArrayList<String>();
List<Integer> listAntenna = new ArrayList<Integer>();
String EPC = null;
String TimeStamp = null;
Integer Antenna = null;
listEPC = readMap.get("epcs");
listTimeStamp = readMap.get("timestamps");
listAntenna = readMap.get("antennas"); //error message here
for(int i=0; i<readMap.size(); i++){
EPC = listEPC.get(i);
TimeStamp = listTimeStamp.get(i);
Antenna = listAntenna.get(i);
System.out.println("Entry " + i );
System.out.println("Values: " + EPC + TimeStamp + Antenna);
}
}
}
This code works only if I change all instances of integers to strings, which is not what I would like in my actual code. Why is it so and how do I work around it?
You can't assign a List<String> to a List<Integer>. The elements are fundamentally different types.
You would need to construct a new List:
List<Integer> listOfIntegers = new ArrayList<>();
for (String entry : listOfStrings) {
listOfIntegers.add(Integer.valueOf(entry);
}
Of course, you also need to handle the possibility that elements of the list cannot be parsed as integers.
However, you are just throwing away type information by stuffing everything into a single map. It would be better to pass the three lists separately:
insertData(listEPC, listTimestamp, listAntenna);
and then you can have different list types in the method signature:
void insertData(
List<String> listEPC,
List<String> listTimestamp,
List<Integer> listAntenna) { ... }
I am going to include the proper answer at the bottom, but in regards to your question title, you'll have to change your method signature to:
LinkedHashmap<String, List<?>> readMap;
Then either cast the lists, which will cause an unsafe cast. eg.
List<String> listEPC = (List<String>)readMap.get("epcs");
Or cast the object.
List<?> listEPC = readMap.get("epcs");
Then in the loop cast.
EPC = (String)listEPC.get(i);
Note, these are not good solutions.
What you should have is one List that contains an object with all of the data's you need.
I can imagine the thought process went something along these lines, "I have these things, and they contain two strings and an integer. I will create a variable for each." Then you ask the question, "How do I create a collection of these things?"
The wrong answer to this question is, "I will make a list for each value, and match associated values by index." The correct answer is, "I will create a class to represent my data, and store that in a list." This is the basic essence of object orient programming (welcome to java).
First we design the class:
class EPCThing{
String EPC;
String timeStamp;
int Antennas;
public EPCThing(String tagId, String timeStamp, int antennas){
EPC=tagId;
this.timeStamp = timeStamp;
Antennas = antennas;
}
#Override
public String toString(){
return "Values: " + EPC + TimeStamp + Antenna
}
}
Now your program's main method will be something like.
List<EPCThing> things = new ArrayList<>();
String tagID = "EQ5237";
String TimeStampStr = "12:23:22";
int tagAntenna = 2;
EPCThing thing = new EPCThing(tagID, TimeStampStr, tagAntenna);
things.add(thing);
insertData insert = new insertData();
insert.insertData(things);
Then we can fix your insertData method
public void insertData(List<EPCThing> things) {
for(int i=0; i<things.size(); i++){
System.out.println("Entry " + i );
System.out.println("Values: " + things.get(i));
}
}
Attempting to tidy up code, originally I was using this method of writing to arrays, which is ridiculously long when I have to repeat it 20 times
if (ant.getAntNumber() == 3)
{
numbers3.add(ant.getCol());
numbers3y.add(ant.getRow());
}
if (ant.getAntNumber() == 4)
{
numbers4.add(ant.getCol());
numbers4y.add(ant.getRow());
}
I attempted to use a for loop to do it but I cant figure out how to add to the array using the string value, because it thinks its a string rather than trying to use the array
for (int j = 0; j<maxAnts; j++)
{
String str = "numbers" + j;
String str2 = "numbers" + j + "y";
//this part doesnt work
str.add(ant.getCol());
}
Any suggestions would be helpful
In Java, you cannot use the value of a String object to reference an actual variable name. Java will think you're attempting to to call add on the String object, which doesn't exist and gives you the compiler error you're seeing.
To avoid the repetition, you need to add your Lists to two master lists that you can index.
In your question, you mention arrays, but you call add, so I'm assuming that you're really referring to Lists of some sort.
List<List<Integer>> numbers = new ArrayList<List<Integer>>(20);
List<List<Integer>> numbersy = new ArrayList<List<Integer>>(20);
// Add 20 ArrayList<Integer>s to each of the above lists in a loop here.
Then you can bounds-check ant.getAntNumber() and use it as an index into your master lists.
int antNumber = ant.getAntNumber();
// Make sure it's within range here.
numbers.get(antNumber).add(ant.getCol());
numbersy.get(antNumber).add(ant.getRow());
How about this?
Ant[] aAnt = new Ant[20];
//Fill the ant-array
int[] aColumns = new int[aAnt.length];
int[] aRows = new int[aAnt.length];
for(int i = 0; i < aAnt.length; i++) {
aColumns[i] = aAnt[i].getCol();
aRows[i] = aAnt[i].getRow();
}
or with lists:
List<Integer> columnList = new List<Integer>(aAnt.length);
List<Integer> rowList = new List<Integer>(aAnt.length);
for(Ant ant : aAnt) {
columnList.add(ant.getCol());
rowList.add(ant.getRow());
}
or with a col/row object:
class Coordinate {
public final int yCol;
public final int xRow;
public Coordinate(int y_col, int x_row) {
yCol = y_col;
xRow = x_row;
}
}
//use it with
List<Coordinate> coordinateList = new List<Coordinate>(aAnt.length);
for(Ant ant : aAnt) {
coordinateList.add(ant.getCol(), ant.getRow());
}
A straight-forward port of your code would be to use two Map<Integer, Integer> which store X and Y coordinates. From your code it seems like ant numbers are unique, i.e., we only have to store a single X and Y value per ant number. If you need to store multiple values per ant number, use a List<Integer> as value type of the Map instead.
Map<Integer, Integer> numbersX = new HashMap<Integer, Integer>();
Map<Integer, Integer> numbersY = new HashMap<Integer, Integer>();
for(Ant ant : ants) {
int number = ant.getAntNumber();
numbersX.put(number, ant.getCol());
numbersY.put(number, ant.getRow());
}
I need to create an Arraylist in a while loop with a name based on variables also in the loop. Here's what I have:
while(myScanner.hasNextInt()){
int truster = myScanner.nextInt();
int trustee = myScanner.nextInt();
int i = 1;
String j = Integer.toString(i);
String listname = truster + j;
if(listname.isEmpty()) {
ArrayList listname = new ArrayList();
} else {}
listname.add(truster);
i++;
}
The variable truster will show up more than once while being scanned, so the if statement is attempting to check if the arraylist already exists. I think I might have done that out of order, though.
Thanks for your help!
Store the ArrayLists in a Map:
Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){
// Stuff
List<String> list = new ArrayList<String>();
list.add(truster);
listMap.put(listname, list);
}
Note the use of generics (the bits in <>) to define the type of Object the List and Map can contain.
You can access the values stored in the Map using listMap.get(listname);
If I understand you correctly, create a list of lists or, better yet, create a map in which the key is the dynamic name you want and the value is the newly created list. Wrap this in another method and call it like createNewList("name").
Really not sure what you mean at all but you have some serious fundamental flaws with your code so I'll address those.
//We can define variables outside a while loop
//and use those inside the loop so lets do that
Map trusterMap = new HashMap<String,ArrayList<String>>();
//i is not a "good" variable name,
//since it doesn't explain it's purpose
Int count = 0;
while(myScanner.hasNextInt()) {
//Get the truster and trustee
Int truster = myScanner.nextInt();
Int trustee = myScanner.nextInt();
//Originally you had:
// String listname = truster + i;
//I assume you meant something else here
//since the listname variable is already used
//Add the truster concated with the count to the array
//Note: when using + if the left element is a string
//then the right element will get autoboxed to a string
//Having read your comments using a HashMap is the best way to do this.
ArrayList<String> listname = new ArrayList<String>();
listname.add(truster);
trusterMap.put(truster + count, listname);
i++;
}
Further, you are storing in myScanner a stream of Ints that will get fed in to the array, but which each have very different meanings (truster and trustee). Are you trying to read these in from a file, or user input? There are better ways of handling this and if you comment below with what you mean I'll update with a suggested solution.
I am attempting to parse the value of the elements in a List declared as thus:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
The values are such as this:
a:1-2
b:3-5
but I want one ArrayList with the first number (i.e. 1, 3) and another with the second (i.e. 2, 5). I have this worked out... Sorta:
String delims= "\t"; String delim2= ":"; String delim3= "-";
String splits2[]; String splits3[]; String splits4[];
Map<String,String> dupMap = new TreeMap<String, String>();
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<String> parsed2 = new ArrayList<String>();
ArrayList<String> parsed3 = new ArrayList<String>();
ArrayList<String> parsed3two= new ArrayList<String>();
double uniques = uniqueList.size();
for(int a=0;a<uniques;a++){
//this doesn't work like it would for an ArrayList
splits2 = uniqueList.split(delim2) ;
parsed2.add(splits2[1]);
for(int q=0; q<splits2.length; q++){
String change2 = splits2[q];
if(change2.length()>2){
splits3 = change2.split(delim3);
parsed3.add(splits3[0]);
String change3=splits3[q];
if (change3.length()>2){
splits4 = change3.split(delims);
parsed3two.add(splits4[0]);
}
}
}
}
uniqueList.split does not work however and I don't know if there is a similar function for List. Is there any suggestions?
If you know that all of your data is in the form [something]:[num]-[num], you can use a regular expression like this:
Pattern p = Pattern.compile("^([^:]*):([^-]*)-([^-]*)$");
// I assume this holds all the values:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for (String src : uniqueList) {
Matcher m = p.matcher(src);
if( m.find() && m.groupCount() >= 3) {
String firstValue = m.group(1); // value to left of :
String secondValue = m.group(2); // value between : and -
String thirdValue = m.group(3); // value after -
// assign to arraylists here
}
}
I didn't actually put the code in to add to the specific ArrayLists because I couldn't quite tell from your code which ArrayList was supposed to hold which value.
Edit
Per Code-Guru's comment, an implementation using String.split() would go something like this:
String pattern = "[:\\-]";
// I assume this holds all the values:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for (String src : uniqueList) {
String[] parts = src.split(pattern);
if (parts.length == 3) {
String firstValue = parts[1]; // value to left of :
String secondValue = parts[2]; // value between : and -
String thirdValue = parts[3]; // value after -
// assign to arraylists here
}
}
Both approaches are pretty much the same in terms of efficiency.
From what I understand of your question, I would proceed as follows:
for each String in uniqueList
parse the string into a character and two integers (probably using a single call to [String.split()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String, int))
insert the first integer into an List
insert the second integer into another List
This is in pseudocode. Translating into Java is left as an exercise to the reader.