I need a Array to PayPal Items must however go another arraylist to add the items as I do that?
ArrayList<PayPalItem[]> stringArrayList = new ArrayList<PayPalItem[]>();
for (int i=0; i<resultado.size(); i++) {
PayPalItem[] items;
double x = Math.round(((resultado.get(i).getTotal() / resultado.get(i).getPreco())));
int quantidade = (int) x;
String preco = String.format("%.2f", resultado.get(i).getPreco());
String nome = resultado.get(i).getProduto();
items = new PayPalItem[]{
new PayPalItem(nome, quantidade, new BigDecimal(resultado.get(i).getPreco()), "BRL",
"dinner")
};
stringArrayList.add(items); //add to arraylist
}
PayPalItem[] items = new PayPalItem[stringArrayList.size()];
//if you want your array
PayPalItem[] stringArray = stringArrayList.toArray(items);
I'm trying to convert an ArrayList to the Array however I get this error
Conversion from an arrayList i.e. ArrayList<Something> list to an Array is done this way (as you already did):
list.toArray(Something[]) <- notice that the parameter here is an array of Something elements.
so in your case: Something is PayPalItem[] then you need to add an extra [] because you have an array of arrays.
replacing your last two lines of your code by these two will solve your issue.
PayPalItem[][] items = new PayPalItem[stringArrayList.size()][];
//if you want your array
PayPalItem[][] stringArray = stringArrayList.toArray(items);
but anyway, I cannot understand why do you need an array of arrays instead of simply just a list or an array. I mean something like this:
ArrayList<PayPalItem> stringArrayList = new ArrayList<PayPalItem>();
for (int i = 0; i < 2; i++) {
//create the PayPalItem and add to the list
stringArrayList.add(new PayPalItem()); //add to arraylist
}
PayPalItem[] items = new PayPalItem[stringArrayList.size()];
//if you want your array
PayPalItem[] stringArray = stringArrayList.toArray(items);
Related
Background:
I am working on a scraping project using Selenium that gets data from tables on webpages in our Test and Production environments and then stores the data into two separate Array List of String type (one for test/prod). The data are numbers (double) and there are 3 columns and anywhere from 13-16 rows of data. It varies because I am pulling data from over 145 countries and each table is different.
Please not that that this is just an example. The code that I present here is not the Selenium Script I am running.
Issue:
The issue lies when I am trying to convert the data from the two Array Lists that I have into two 2 dimensional arrays. I have worked with very basic 2d arrays before, but only created them off of user input.
Based on the research I have done before, the syntax for converting an ArrayList to an array is:
ArrayList<String> b = new ArrayList<>();
b.add("1.50");
b.add("3.12");
b.add("5.25%");
b.add("2.16");
b.add("4.36");
b.add("7.76%")
//This is just a snippet, remember the list would have anywhere from 13-16
indices.
String[] x = b.toArray();
But how do I convert that same list into an 2 dimensional array in the format of
1.50 3.12 5.25%
2.16 4.36 7.76%
starting a new line every third index?
You have to loop the List and add the items to a new one unless you find value with a percentage (%) in it. Then, you create a new List. This solution is based on the % character appearance, not the fixed size of a gap between elements to split which might be an advantage.
List<List<String>> outer = new ArrayList<>();
List<String> inner = new ArrayList<>();
for (String s: b) {
inner.add(s);
if (s.contains("%")) {
outer.add(inner);
inner = new ArrayList<>();
}
}
The List<List<String>> outer will contain these values:
[[1.50, 3.12, 5.25%], [2.16, 4.36, 7.76%]]
To convert the structure from List<List<String>> to String[][], you can use java-stream or a simple for-loop approach iterating and filling the array.
String[][] array = outer.stream()
.map(a -> a.stream().toArray(String[]::new)) // List<String> to String[]
.toArray(String[][]::new); // List<String[]> to String[][]
A typical for loop should do:
List<List<String>> accumulator = new ArrayList<>();
for (int i = 0; i < b.size(); i+=3) {
List<String> temp = new ArrayList<>(b.subList(i, i + 3));
accumulator.add(temp);
}
accumulator now looks like:
[[1.50, 3.12, 5.25%], [2.16, 4.36, 7.76%]]
note that the above assumes you'll always a list that is a multiple of three, if that it not the case then you can handle it as follows:
List<List<String>> accumulator = new ArrayList<>();
for (int i = 0; i < b.size(); i+=3) {
List<String> temp = b.stream().skip(i).limit(3).collect(toList());
accumulator.add(temp);
}
if you strictly require the result to be a String[][] then you can get it as follows:
String[][] strings =
accumulator.stream()
.map(l -> l.toArray(new String[0]))
.toArray(String[][]::new);
You can iterate over your list an add the entries manually in an 2d-array:
String[][] array = new String[b.size()/3][3];
for (int i = 0; i < b.size(); i++) {
int row = i / 3;
int col = i % 3;
array[row][col] = b.get(i);
}
System.out.println(Arrays.deepToString(array));
Lets say you have an array like this: String[] theWords = {"hello", "good bye", "tomorrow"}. I want to remove/ignore all the strings in the array that have the letter 'e'. How would I go about doing that? My thinking is to go:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
I'm not sure if my logic works and if I'm even on the right track. Any responses would be helpful. Many thanks.
One easy way to filter an array is to populate an ArrayList with if in a for-each loop:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Another way in Java 8 is to use Collection#removeIf:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
Or use Stream#filter:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
You can directly use contains() method of String class to check if "e" is present in your string. That will save your extra for loop.
It would be simple if you use ArrayList.
importing import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
The problem you have is that you need to declare and instantiate the String array before you even know how many elements are going to be in it (since you wouldn't know how many strings would not contain 'e' before going through the loop).
Instead, if you use an ArrayList you do not need to know the required size beforehand. Here is my code from start to end.
String[] theWords = { "hello", "good bye", "tomorrow" };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));
This is what I have
ArrayList <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
Collections.sort(cdList, String.CASE_INSENSITIVE_ORDER);
System.out.println(cdList);
bigBox.setText("Original Order\n**************\n");
for (int i = 0; i < cdList.size(); i++) {
bigBox.setText(bigBox.getText()+""+cdList.get(i)+"\n");
}
bigBox.setText(bigBox.getText()+"\n\nSorted Order\n************\n");
Collections.sort(cdList);
for (int j = 0; j < cdList.size(); j++) {
bigBox.setText(bigBox.getText()+""+);
}
I want the 4 examples outputted in their original order, and in alphabetical order. What am I doing wrong?
You are adding only one element (String) to the list, a concatenated string.
Change this
ArrayList <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
to
List <String> cdList = new ArrayList<String>();
Collections.addAll(cdList, "ExampleA","ExampleB","ExampleC","ExampleD");
Read more Collections#addAll
And for showing you should use append rather than setText.
Example:
bigBox.append("Original Order\n**************\n");
for (String s : cdList) {
bigBox.append(s);
bigBox.append("\n");
}
I assume your elements are meant to be the strings "ExampleA", "ExampleB", "ExampleC", and "ExampleD". If the is the case, what you are currently doing in your call to Collections.addAll() is adding them to cdList as one long string. the + operator, when used on strings, appends them. What you probably want it to separate them with commas, so that instead of having:
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
you have:
Collections.addAll(cdList, "ExampleA\n", "ExampleB\n", "ExampleC\n", "ExampleD");
Please help me to convert ArrayList to String[]. The ArrayList contains values of type Object(VO).
For example,
The problem is that I need to convert a country List to String Array, sort it and then put it in a list. However I am getting a ClassCastException.
String [] countriesArray = countryList.toArray(new String[countryList.size()]);
I have assumed that your country List name is countryList.
So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.
List<T> list = new ArrayList<T>();
T [] countries = list.toArray(new T[list.size()]);
Please help me to convert ArrayList to String[], ArrayList Contains
Values Object(VO) as Values.
As you mentioned that list contains Values Object i.e. your own class you need toString() overridden to make this work correctly.
This code works. Assuming VO is your Value Object class.
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] result = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
result[i] = listOfValueObject.get(i).toString();
}
Arrays.sort(result);
List<String> sortedList = Arrays.asList(result);
The snippet of
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] countriesArray = listOfValueObject.toArray(new String[listOfValueObject.size()]);
will give you ArrayStoreException due VO is not the String type as required by native method arraycopy subsequently called from toArray one.
In case your ArrayList contains Strings, you can simply use the toArray method:
String[] array = list.toArray( new String[list.size()] );
If that is not the case (as your question is not completely clear on this), you will have to manually loop over all elements
List<MyRandomObject> list;
String[] array = new String[list.size() ];
for( int i = 0; i < list.size(); i++ ){
MyRandomObject listElement = list.get(i);
array[i] = convertObjectToString( listElement );
}
String[] array = list.toArray(new String[list.size()]);
What are we doing here:
String[] array is the String array you need to convert your
ArrayList to
list is your ArrayList of VO objects that you have in hand
List#toArray(String[] object) is the method to convert List objects
to Array objects
As correctly suggested by Viktor, I have edited my snippet.
The is a method in ArrayList(toArray) like:
List<VO> listOfValueObject // is your value object
String[] countries = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
countries[i] = listOfValueObject.get(i).toString();
}
Then to sort you have::
Arrays.sort(countries);
Then re-converting to List like ::
List<String> countryList = Arrays.asList(countries);
Prior to Java 8 we have the option of iterating the list and populating the array, but with Java 8 we have the option of using stream as well. Check the following code:
//Populate few country objects where Country class stores name of country in field name.
List<Country> countries = new ArrayList<>();
countries.add(new Country("India"));
countries.add(new Country("USA"));
countries.add(new Country("Japan"));
// Iterate over list
String[] countryArray = new String[countries.size()];
int index = 0;
for (Country country : countries) {
countryArray[index] = country.getName();
index++;
}
// Java 8 has option of streams to get same size array
String[] stringArrayUsingStream = countries.stream().map(c->c.getName()).toArray(String[]::new);
I have an ArrayList named play_viewCount: I am sorting this ArrryList and storing it in a new ArrayList.
Now I have sorted ArrayList: but what I want is before sorting what was the position of new items in ArrayList?
ArrayList<String> sort_play_viewCount = play_ViewCount; // here play_viewCount is ArrayList
ArrayList<Integer> position_array = new ArrayList<Integer>();
System.out.println("......................................... Play Count :"+sort_play_viewCount);
Collections.sort(sort_play_viewCount);
System.out.println(".........................................sort Play Count :"+sort_play_viewCount);
for(int j = 0; j<sort_play_viewCount.size(); j++){
for(int k = 0; k<sort_play_viewCount.size(); k++){
if(play_ViewCount.contains(sort_play_viewCount.get(j))){
position_array.add(k);
}
}
}
System.out.println(" .................Position Array: "+position_array);
Does anyone know how to get the positions of the new items before sorting?
Try doing a little differently:
ArrayList<Integer> position_array = new ArrayList<Integer>();
position_array.addAll(play_viewCount);
Collections.sort(position_array);
Now position_array is sorted, and to get the previous positions you can just call play_viewCount.indexOf(value);
You can put the elements of the ArrayList into a Map<String, Integer> (implemented by a HashMap<String, Integer>), where the key of an entry is String element from the ArrayList and the value is Integer representing the position.
Map<String, Integer> originalPositions = new HashMap<String, Integer>();
String item = ...
String position = ...
originalPositions.put(item, position);
// do something with the ArrayList, such as sorting
Collections.sort(arrayList);
String someItem = arrayList.get(i);
int originalPosition = originalPositions.get(someItem);
And by the way, this line from your code snippet doesn't do what you think it does:
ArrayList<String> sort_play_viewCount = play_ViewCount;
It doesn't create a new ArrayList with the same contents as the original one. Instead, it just creates a new reference to the original ArrayList. Both play_ViewCount and sort_play_viewCount refer to the very same object, in other words, any changes to one of the variables (such as sorting) also affect the other one.
To create a new copy (however, it is still shallow) of an ArrayList, use the following idiom:
ArrayList<Integer> original = ...
ArrayList<Integer> copy = new ArrayList<Integer>(original);