I have two arrays and i want to access data of same index value from other array.
Two Array list :
ArrayList<Integer> Position = new ArrayList<Integer>();
ArrayList<String> List_Data = new ArrayList<String>();
Now my Position array contains Integer value like index of data i.e 0,3,5 out of 10 Records.
i want to get only those string whose index should be i.e 0,3,5 out of 10 .
Example :
String Array >> [A,B,C,D,E,F,G,H,J,K];
Index >> Now i am selecting 2 ,5 index data.
Final Output as string >> C,F
So at the end i get actual string from array.
I get this and some other link also but not get exact idea how to do this.
Please anyone help me.
Try this, If I understand what you want correctly (otherwise let me know)
String sr=Lista_Data.get(Position.get(INDEX YOU NEED; EG 1, 5, 1000...))
You can get object from ArrayList using get function. Then you can use it as an index to another ArrayList.
String res = "";
for (Integer pos : Position) {
res += List_Data.get(Position.get(pos));
}
The only thing you need is method indexOf(...) of List.
public String getStringByIndex(Integer index) {
return List_Data.get(Position.indexOf(index));
}
I am not not saying that above code is wrong but its not working according my needs. or i can't handle because of my other code limitation.
Finally, I get as i want like :
for (int i = 0; i < Poisition.size(); i++)
{
System.out.println("Selected Data --->"+ List_Data.get(Poisition.get(i)));
}
Related
Automation scenario is to get all the links in weblist & then get this arraylist content outside loop and then get the index number dynamically based on the url hit.
String values="";
List<WebElement> url_link = driver.findElements(By.cssSelector(".anomaly>a"));
for ( WebElement we: url_link) {
String temp = values;
values = temp + we.getText();
}
System.out.println("Text "+values);
int ind=values.indexOf("www.test.com");
System.out.println("Index "+ind);
The above code returns me a weird index number of 74.
The url_link output contents are:
wwww.hatch.com
wwww.tist.com
wwww.helix.com
wwww.patching.com
wwww.seyh.com
wwww.test.com
wwww.toast.com
wwww.telling.com
wwww.uity.com
so based upon the expected result i am expecting the index number to be 5.
Any help will be appreciated.
The variable values is a variable of type String, it's not a List. So when you do values = temp + we.getText();, you are basically appending all the links in a single String. So the output will actually be this:
wwww.hatch.comwwww.tist.comwwww.helix.comwwww.patching.comwwww.seyh.comwwww.test.comwwww.toast.comwwww.telling.comwwww.uity.com
The index of www.test.com is 74 in this string. You should be adding these links in an ArrayList and then find the index of the link you want to search.
Something like this should work:
List<String> values = new ArrayList<String>();
List<WebElement> url_link = driver.findElements(By.cssSelector(".anomaly>a"));
for ( WebElement we: url_link) {
values.add(we.getText());
}
int ind = values.indexOf("www.test.com");
System.out.println("Index "+ind);
ArrayList<String> str = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
str.add(s1);
str.add(s2);
I want to compare a string to one of the elements of the array.
String b = "Test1";
b.equals(str[index??]);
How can i get the index of str?
It's an arrayList. Therefore, to store a value of the array with a certain index, use this:
ArrayList.get(index);
Now, you can make this equal to a variable like this:
String mStr = ArrayList.get(index);
If I have an arrayList with the values "1, 2, 3, 4" it's important to note, index 0 is the value 1.
ArrayList.get(0) //HERE, THE INDEX IS ZERO, MEANING THE VALUE OF THE ARRAY LIST WOULD BE 1
Output:
1
That is easily confused; index 0 = first value. Just be sure to use the get() method.
To further compare strings, set that values equal to strings:
String FIRSTSTRING= ArrayList.get(0);
String SECONDSTRING= ArrayList.get(1);
Here, I am comparing the first and second values of the array list.
If you found this helpful, mark it as best answer. If you need more help, feel free to ask me, I am always happy to help!
{Ruchir}
You want List.get(int) (where int is the index). For example,
List<String> al = Arrays.asList("Test1", "Test2");
System.out.println(al.get(0).equals("Test1"));
the output is
true
You can try something like this
ArrayList<String> str = new ArrayList<String>();
...
boolean found = false;
for(String string : str)
found =b.equals(string);
Other than that,you can use get method of list.
You can use indexOf() method.
ArrayList<String> str = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
str.add(s1);
str.add(s2);
System.out.println(str.indexOf("Test1"));
If you want to use the str.get(index) method and then check use a loop, But I find this more complicated.
for(int i = 0; i < list.size(); ++i)
if(list.get(i).equals("rtes"))
return i;
Use Binary Search if your Array is sorted. Otherwise, just go linearly in the arraylist, and compare the values.
in your case:
boolean find = false;
for(i=0;i<str.length;i++){
if(str.get(i) == b){
find = true;
break;
}
}
I'm looping into a number of rows and trying to filter these rows with some if statements. within each if statement I need to have an index for a number of elements. I could have done that using 2d String[][] but the problem is I don't know what is the size of each row at this stage.
I'm looking to store my data like the following :
0 1 3 4 5 6 7 etc..
0 str str str str str str str
1 str str str
2
3 str str str str str str
Any suggestion would be appreciate it
Edit:
Sorry if my question wasn't clear. But I'll explain it more here.
My Loop looks like this:
newArrayList
for (i; i < List ;i++)
{
if(...)
{
newArrayList.add.(0, List.get(i));
} else if(...)
{
newArrayList.add.(2, List.get(i));
} else if(...)
{
newArrayList.add.(6, List.get(i));
}
}
The above code doesn't work but I'm just trying to explain what I need to do actually! My if statements can occur several times and I would like to consider an index for each if statement expectation plus a set of strings. Thanks.
You could try an ArrayList of ArrayList's:
ArrayList<ArrayList<String>> strings = new ArrayList<ArrayList<String>>();
strings.add(new ArrayList<String>()); // Adding a first array to the 'array of arrays'
strings.get(0).add("String1"); // Add a string to the first array,
// Similar to: arr[0][0] = "String1"
//To access them element by element use a double for, note that "s" is each element
for (ArrayList<String> l : strings) {
for (String s : l) {
}
}
PS: An ArrayList<Object> is like an array Object[] but more flexible. It has some useful methods like:
arr_list.get(index); // Getting an object in position 'index'
arr_list.add(object); // Adding an element (Similar to assignment in arrays)
Edit
If you know the number of "rows" then you have to add them to the array of arrays. With this for you are "creating the empty rows of your array":
Rows:
0
1
...
n
for (int i = 0; i < n; i++) { // n is the number of "rows"
strings.add(new ArrayList<String>());
}
Then add an element to a "row":
strings.get(0).add("String1"); // get(0) to obtain the first row, get(1) to obtain the second...
If your index is consecutive form 0 to n and you are inserting them in that order, but n is not known in advance: There are two classical solution:
1) If you do it with a pre-allocated fixed array, you obviously need two passes. The first pass is scanning the row and counting the elements. The second pass is then creating the index.
2) You can do it with a collection allowing dynamic growth via an .add(item) method, like List
If you will convert the collection to an fixed size array later, then it is maybe faster to use method 1) since the add method may be slower due to memory management / allocation / re-allocation.
If your index is consecutive form 0 to n and n is known in advance, but you are inserting the elements not in that order:
You should use solution 1) above.
If your index is not consecutive and n is known known in advance:
3) You create a Map<Integer,String> strings and add the elements via strings.put(index, string) (in any order).
If your index is not unique (as we have finally found out):
4) You crate a Map<Integer,ArrayList<String>> stringMap and add elements via
addStringForIndex(String string, Integer index)
{
listForString = stringMap.get(index);
if(listForString == null) {
listForString = new ArrayList<String>;
map.put(index, listForString);
}
listForString.add(string);
}
If you don't know the size of your array, you could use a List implementation, for example:
ArrayList<ArrayList<String>> 2D = new ArrayList<ArrayList<String>>();
And then use a for-each loop
Hi I'm not sure if this is a problem with Eclipse or Java but recently my code has stopped working. I only changed things like assigning new variables to store things. My program takes a multi-dimensional string array and should return a new array trimmed of nulls.
public void makebuttons(final int n, String equals) {
//does lots of widget functions and id assignments
String[] items=getArray(Integer.parseInt(data.equnits.substring(n*3, n*3+1)));
unitvalues[n]=Integer.parseInt(data.equnits.substring(n*3, n*3+1));
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item, items);
//does more code
}
public static String[] getArray(int selection) {
String[] result;//stores the new array
int x=0,j=0 ,ulength = data.units[0].length;//ints used
String temp="";
while(j < ulength && temp!=null) {
temp= data.units[selection][j][0]; //find the actual array length
j++;
}
if(j==ulength)j--;
result = new String[j+1];//initalise array from check
for(x=0; x<=j; x++) { //add data to array
result[x]=data.units[selection][x][0];
}
return result;//return corrected array
}
Integer.parseInt and Integer.valueOf give value of 0 each time for a string like "01,02,03,04" data.equnits stores the string to be converted to integer by checking 2 digits only to select from a large 3 dimensional array. Since its a 3 dimensional array some nulls are present
Null check for the String doesnt seem to work since the while loop doesnt seem to detect it and it ends up being in the array that gets passed into the array adapter for spinner causing NullPointerException while scrolling.
Restarting eclipse doesn't help.
I can't help with your first problem without more information, but this seems to be the issue with your second:
The function substring is inclusive of the first parameter and exclusive of the second. Since you are only adding 1 to the n*3, you only get one character.
Try using:
substring(n*3, n*3+2)
Edit:
Adding the updated code from my comment above:
while(j < ulength && temp != null && !temp.isEmpty())
{
temp = data.units[selection][j];
j++;
}
I have an ArrayList which contains duplicate values at diff diff index.
for example {"Indian","American","Chinese","Australian","Indian","Russian","Indian"}
as u can see the value - "Indian" exists at index - 0, 4 & 6.
I need to know all these indexes where "Indian" exists and create an arrayList of that.
Here is my code:
public void filter(){
categoryArray = Arrays.asList(category);
for(String k : category){
//Log.v("filter", filterTerm);
if(k.equals(filterTerm.toLowerCase()))
{
int p = categoryArray.indexOf(k);
Log.v("index of categArr", ""+p);
String id = Integer.toString(p);
indexes.add(id);
}// end of if
}// end of for
Here I get how many times duplicate occurs by getting the size of indexes(ArrayList)
but when I check the values . Its one value at all index since in the method : indexOf() it always brings the index of first value that it finds in the Array.
So if duplicate exists at index - 2,5,7
I get the array size of index as 3.
But the values are {2,2,2,};
This is a situation where an index-based for loop is more appropriate than enhanced for loop that you're using, as what you need to grab is the index.
You can base all your work on the original array rather than converting it to a list, and I suspect you were going for case-insensitive match.
public void filter(){
for(int i=0; i<category.length; i++){
if(category[i].equalsIgnoreCase(filterTerm))
{
String id = Integer.toString(i);
indexes.add(id);
}
}
}
If you have an ArrayList rather than an array, of course similar code will work, but using list.get(i) instead of category[i].
You need to know which index in the array you are currently at, not the first index where it is to be found. To keep track of that, put
int i = 0;
before the loop, and at the very end of the loop put
i++;
Then the variable i tells you where you have found the value, so you can add i to the indexes list.