Adding data to an ArrayList repeatedly - java

I am trying to add 100 (realistically more) Strings to an ArrayList. Instead of adding each String individually, how can I use something like a for loop to add them at once. The code below is an example.
ArrayList<String> strings = new ArrayList();
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
/*
More Strings created until the 100th String
.
.
.
*/
String s100 = "Kiwi";
//for loop to try add each String to List
for(int i=0; i<100; i++)
{
//Code to add each String to the arraylist
}
Can anyone identify the how I can add each String to the list?
Thanks much appreciated

Well, you could create a sophisticated strategy using reflection to fetch all variables of a given class and add them to a List; subsequently, you could loop this List and do whatever you want.
However, I do not think it would solve your problem. Indeed, you are likely to run into several pitfalls.
I would change your approach to the problem. Create a static List and add whatever you need there (or a Singleton, it depends how you want to manage this List). Once you have the list of objects you can loop it.
Cheers,

From your comments you are dealing with custom objects. Regardless of how you want to transfer data from the objects into your ArrayList, better to use a collection. The type of the collection will depend on the source of your object data. As the data is hard-coded you could use an array. Multiple variables like these
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
become
String[] fruitArray = {
"Apple",
"Banana",
"Pear"
...
};
Then to add:
for (String fruit: fruitArray) {
strings.add(fruit);
}
As already stated my comment above, a cleaner design would be to to use a single List<MyObject> to contain all objects in a DRY approach and just extract a String as needed.

Related

use dynamic string to refer to arraylist

I think it can be explained better with example:
I have arrayLists by names sname,stime,snumber,etc., each carrying different values
and a dynamic string 'dString' that is a concatenation of "s" and a variable VR that carries (name, time, number, etc.).
Bbased on the value of VR i get from a loop, i'd like to use respective arraylist in a method. How can i use dString to refer to respective arraylist?
ArrayList<String> sname = new ArrayList<>();
ArrayList<String> stime= new ArrayList<>();
ArrayList<String> snumber = new ArrayList<>();
String[] VR = {"name","time","number"};
for(String str:VR) {
String dString = "s"+str;
String temp= dString.get(2); //How to get this?
}
(This is just as an example. the arraylists aren't empty. it's a long program so i haven't included it).
The answer is: you should be using a Map.
That is the data structure that Java offers you to map a value (for example a List of Strings) to a key (for example: a String).
In other words: don't invent your own "dictionary", when the language already offers that concept to you.
Beyond that, the real answer would be to go "full" OOP. Meaning: you shouldn't have three different lists that together describe some object (linked by a common index). Instead you rather create a class that has name, title, and number fields. So that you only hold one list of such objects.

Custom method for ArrayList

Hello I would like to make a custom method for ArrayList class.
So lets say I make a new ArrayList.
ArrayList<String> list = new ArrayList<String>
I would like to make a method I can call on list.
Something like this:
list.myMethod();
What I want to solve with my method is so you can get an Object by Object name and not index inside the ArrayList.
So basically I want to make a method returning following:
list.get(list.indexOf(str));
To sum it up:
ArrayList<String> list= new ArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.get(0));
System.out.println(list.get(list.indexOf(str)));
Will print: "asd" "asd".
So instead of writing: list.get(list.indexOf(Object))
I would like to be a able to write list.myMethod(Object) and get the same result. I hope you understand my question. I know this is probably a dumb solution and I could just use a Map. But this is for learning purpose only and nothing I will use.
Custom method >>
public class MyArrayList<E> extends ArrayList<E> {
public E getLastItem(){
return get(size()-1);
}
}
How to use it >>
MyArrayList<String> list= new MyArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.getLastItem());
what you need requires to extend the ArrayList classs, but you should consider using instead a
Map<String, Object>
with that approach you can do something like
myMap.get("myObject1");
You should just extend the ArrayList class creating your own with the new method. But the performance would be horrible if your list grow too much. The indexOf method have O(n), so greater is the size of your array longer is the time you have to wait.
May be you should choose a different collection if you want access directly to the element. In your case, it elements stored in the collection are unique, you could use a Set.
On the other hand, a Set does not preserve the insertion order. I don't know if this is a think you have to care of.
And a Set just let you know if the element is contained into the collection.
Another collection that can be of your interest is the Map, this is a key-value collection.
But given that you have only keys this it seems not be your case.

How to Sort Numeric Array in JMeter Beanshell

I am new to using Beanshell/Java in my JMeter scripts. I have following code in my JMeter Beanshell Processor.
int count = Integer.parseInt(vars.get("student_id_RegEx_matchNr"));
String delimiter = ",";
StringBuffer sb = new StringBuffer();
for(int i=1;i<=25;i++) {
sb.append(vars.get("student_id_RegEx_" + i));
if (i == count){
break; //to eliminate comma after the array
}else {
sb.append(delimiter);
}
}
vars.putObject("myUnsortedVar",sb.toString());
I get following as output when I run script:
myUnsortedVar=5,6,2,3,1,4
I want it to be sorted numerically like this and also stored in a new variable named "sortedVar".
1,2,3,4,5,6
What code can I use to sort this and also store in a new variable so I can use the sorted array in coming JMeter requests. Thanks for help.
Taking sb.toString() = "5,6,2,3,1,4".
Use String::split() to convert from String to String[].
Use Arrays::sort() to sort the array
Use Arrays.toString() to convert from String[] to String
String[] sortedArray = Arrays.sort(sb.toString().split(","));
vars.putObject("mySortedVar", Arrays.toString(sortedArray));
I suppose that in bean shell you may use the same as in Java. Once you fill StringBuffer, there is not easy way to sort the contents. Therefore I would store the contents first into an intermediate ArrayList<String> (or even better ArrayList<Integer> if you always get numbers), then sort it using Collections.sort, and then use another for cycle to put the list's contents into StringBuffer using the comma delimiter.
You could do something like:
char [] responseCharArray = vars.get("myUnsortedVar").toCharArray();
Arrays.sort(responseCharArray);
String mySortedString = Arrays.toString(responseCharArray);
vars.put("mySortedVar", mySortedString.replaceAll("\\,\\,","").replaceAll(" ",""));
See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting in JMeter
As OndreJM suggested, you need to change your approach. Instead of storing values in StringBuffer, store them in ArrayList and then use Collections.sort to sort it. Following code should work for you.
// create an ArrayList
ArrayList strList = new ArrayList();
for (int i=0;i<25; i++){
strList.add(vars.get("student_id_RegEx_" + String.valueOf(i+1)));
}
// sort this ArrayList
Collections.sort(strList);
// use StringBuilder to build String from ArrayList
StringBuilder builder = new StringBuilder();
for (String id: strList){
builder.append(id);
builder.append(",");
}
builder.deleteCharAt(builder.length()-1);
// finally put in variable using JMeter built in 'vars.put'
// do not use vars.putObject, as you can not send object as request parameter
vars.put("sortedVar", builder.toString());

Comparing a string in a string object using java

I'm having a config entry, from which I'm loading into an String array like
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
Here I'm comparing a string with the array values after splitting it like ,
for(String arrNewErrorInfo : scbHLNewArray) {
LOG.info("SCB HL New Error Value :"+arrNewErrorInfo+"\n");
if(errorInfo.equals(arrNewErrorInfo)) {
LOG.info("SCB HL Matched New value is :"+arrNewErrorInfo);
newState = ApplicationState.NEW;
addApplicationEvent(application.getId(),comment, ApplicationEventType.COMMENT,BBConstants.AUTOBOT);
scbHLNewStatus = "Matched";
break;
}
}
I want to use some util classes like List.. Any idea on append to list and compare the string with the list objecT?
Thanks,
Nizam
you can do this with List contains method.
ArrayList<Integer> arrlist = new ArrayList<Integer<(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
// list contains element 10
boolean retval = arrlist.contains(10); // It will return true.
Ok, let's try... First of all, you can create a List Object, wrapping your array very easily:
List<String> myList = Arrays.asList( scbHLNewArray );
Be carefull, because you can NOT add to this list, as it only wraps your array. If you want a list you can add to, you would have to create a new one, for example:
List<String> myModifiableList = new ArrayList<String>( myList );
This will create a new List that contains all the Strings from the first one but is also modifiable (you can add Strings, if you want).
In any case, you can use "contains", as Pratik has already shown, to test if a String is inside your list:
if (myList.contains("someString")) { ... }
This works because the String class already has well implemented equals(...) and hashCode() methods. If you want to put other Object than Strings into your list, you would have to make sure that these methods are implemented well, otherwise contains might not work as expected.
Yes you can use a list of course, you need to :
1. Take the result of split as an array.
2. Then convert this array to a list.
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
List<String> list=Arrays.asList(scbHLNewArray); //convert the array to a list
Take a look at Arrays.asList(Array a) and this Tutorial for further information about it.
And then to search the wanted String object you can use indexOf(Object o) or contains(Object o) List methods

Collections.sort(String), doesn't work for me?

ok. Rookie question.
I have a scanned string that i would like to sort using Collections.sort(string).
The string comes from a scanned file that has a bunch of "asdfasdfasdf" in it.
I have scanned the file (.txt) and the scannermethod returns a String called scannedBok;
The string is then added to an ArrayList called skapaArrayBok();
here is the code:
public ArrayList<String> skapaArrayBok() {
ArrayList<String> strengar = new ArrayList<String>();
strengar.add(scanner());
Collections.sort(strengar);
return (strengar);
}
in my humble rookie brain the output would be "aaadddfffsss" but no.
This is a schoolasigment and the whole purpose of the project is to find the 10 most frequent words in a book. But i can't get it to sort. But i just would like to know why it won't sort the scanned string?
You are sorting the list, not the String. The list has only one element, so sorting it doesn't change anything.
In order to sort the content of the String, convert it to an array of characters, and sort the array.
Collections.sort() sorts the items in a list.
You have exactly one item in your list: the string "aaadddfffsss". There's nothing to sort.
SUGGESTIONS:
1) Read more strings into your collection
public ArrayList<String> skapaArrayBok() {
ArrayList<String> strengar = new ArrayList<String>();
// Input three strings
strengar.add(scanner());
strengar.add(scanner());
strengar.add(scanner());
// Now sort
Collections.sort(strengar);
... or ...
2) Split the string into characters, and sort the characters.
public ArrayList<String> skapaArrayBok() {
// Get string
String s = scanner());
char[] charArray = s.toCharArray();
Arrays.sort(charArray );
// Return sorted string
return (new String(charArray);
It is correct to sort "strengar", the ArrayList. However, it would not change the ordering of the ArrayList if you've only added one String to it. A list with one element is already sorted. If you want to sort the ArrayList, you should call add() on the ArrayList with each String you need to add, then sort.
You want to sort the characters within the String which is completely different and you need to re-organize the characters, a possible solution (especially knowing that Strings are immutable) is the following Sort a single String in Java

Categories