Getting Index of Arraylist in Java - java

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;
}
}

Related

Split a field through array in java

I would like to know how to split a field through array using Java. For example we have GLaccount like AAAA-BBBB-CCCC and we would like to split each component and store it in an variable however the GLaccount may have AAAA-BBBB (no third component) so in this case variable segment3 throws NULL POINTER exception so I am not sure on how to fix this since I am new to Java.
String GL = getOwner().getGL("GLACCT");
String segment1 = GL.split("-")[0];
String segment2 = GL.split("-")[1];
String segment3 = GL.split("-")[2];
Using split("-" ) will give you an array of strings.
before using array value, you can check the size of array that if it contains enough elements to use..
String GL = getOwner().getGL("GLACCT");
String[] array=GL.split("-");
String segment1 = array[0];
String segment2 = array[1];
//check if array have 3rd element
if(array.length >2)
String segment3 = array[2];
else
System.out.println("No third element") ;
Use split method (once) and check returned array length :
String[] values3 = "AAAA-BBBB-CCCC".split("-");
// values.length == 3
String[] values2 = "AAAA-BBBB".split("-");
// values2.length == 2
import java.util.Arrays;
List<String> list = Arrays.asList(GL.split("-"));
With this code you do not need to think if you have 2,3 or 10 strings, and to add new if for every new one.

Search array for value containing all characters(in any order) and return value

I've searched high and low and finally have to ask.
I have an array containing, for example, ["123456","132457", "468591", ... ].
I have a string with a value of "46891".
How do I search through the array and find the object that contains all the characters from my string value? For example the object with "468591" contains all the digits from my string value even though it's not an exact match because there's an added "5" between the "8" and "9".
My initial thought was to split the string into its own array of numbers (i.e. ["4","6","8","9","1"] ), then to search through the array for objects containing the number, to create a new array from it, and to keep whittling it down until I have just one remaining.
Since this is likely a learning assignment, I'll give you an idea instead of an implementation.
Start by defining a function that takes two strings, and returns true if the first one contains all characters of the second in any order, and false otherwise. It should looks like this:
boolean containsAllCharsInAnyOrder(String str, String chars) {
...
}
Inside the function set up a loop that picks characters ch from the chars string one by one, and then uses str.indexOf(ch) to see if the character is present in the string. If the index is non-negative, continue; otherwise, return false.
If the loop finishes without returning, you know that all characters from chars are present in src, so you can return true.
With this function in hand, set up another loop in your main function to go through elements of the array, and call containsAllCharsInAnyOrder on each one in turn.
I think you can use sets for this.
List<String> result = new ArrayList<>();
Set<String> chars = new HashSet<>(Arrays.asList(str.split(""));
for(String string : stringList) {
Set<String> stringListChars = new HashSet<>(Arrays.asList(string.split(""));
if(chars.containsAll(stringListChars)) {
result.add(string);
}
}
There is a caveat here; it doesn't work as you would expect for repeated characters and you haven't specified how you want to handle that (for example, 1154 compared against 154 will be considered a positive match). If you do want to take into account repeated characters and you want to make sure that they exist in the other string, you can use a List instead of a Set:
List<String> result = new ArrayList<>();
List<String> chars = Arrays.asList(str.split(""));
for(String string : stringList) {
List<String> stringListChars = Arrays.asList(string.split("");
if(chars.containsAll(stringListChars)) {
result.add(string);
}
}
Your initial idea was good start, so what you can do is to create not an array but set, then using Guava Sets#powerSet method to create all possible subsets filter only those that have "46891".length mebers, convert each set into String and look those strings in the original array :)
You could do this with the ArrayList containsAll method along with asList:
ArrayList<Character> lookingForChars = new ArrayList<Character>(Arrays.asList(lookingForString.toCharArray()));
for (String toSearchString : array) {
ArrayList<Character> toSearchChars = new ArrayList<Character>(Arrays.asList(toSearchString.toCharArray));
if (toSearchChars.containsAll(lookingForChars)) {
System.out.println("Match Found!");
}
}
You can use String#chartAt() in a nested for loop to compare your string with each of the array's elements.
This method would help you check whether a character is contained in both strings.
This is more tricky then a straigt-forward solution.
The are better algorithms but here one easy to implement and understand.
Ways of solving:
Go through every char at your given string and check if it at the
given arrray.
Collect list for every string from the selected
array containing the given char.
Check if no other char to check.
If there is, Perform A again but on the collected list(result list).
Else, Return all possible matches.
try this
public static void main(String args[]) {
String[] array = {"123456", "132457", "468591"};
String search = "46891";
for (String element : array) {
boolean isPresent = true;
for (int index = 0; index < search.length(); index++) {
if(element.indexOf(search.charAt(index)) == -1){
isPresent = false;
break;
}
}
if(isPresent)
System.out.println("Element "+ element + " Contains Serach String");
else
System.out.println("Element "+ element + " Does not Contains Serach String");
}
}
This sorts the char[]'s of the search string and the and the string to search on. Pretty sure (?) this is O(n logn) vs O(n^2) without sorting.
private static boolean contains(String searchMe, String searchOn){
char[] sm = searchMe.toCharArray();
Arrays.sort(sm);
char[] so = searchOn.toCharArray();
Arrays.sort(so);
boolean found = false;
for(int i = 0; i<so.length; i++){
found = false; // necessary to reset 'found' on subsequent searches
for(int j=0; j<sm.length; j++){
if(sm[j] == so[i]){
// Match! Break to the next char of the search string.
found = true;
break;
}else if(sm[j] > so[i]){ // No need to continue because they are sorted.
break;
}
}
if(!found){
// We can quit here because the arrays are sorted.
// I know if I did not find a match of the current character
// for so in sm, then no other characters will match because they are
// sorted.
break;
}
}
return found;
}
public static void main(String[] args0){
String value = "12345";
String[] testValues = { "34523452346", "1112", "1122009988776655443322",
"54321","7172839405","9495929193"};
System.out.println("\n Search where order does not matter.");
for(String s : testValues){
System.out.println(" Does " + s + " contain " + value + "? " + contains(s , value));
}
}
And the results
Search where order does not matter.
Does 34523452346 contain 12345? false
Does 1112 contain 12345? false
Does 1122009988776655443322 contain 12345? true
Does 54321 contain 12345? true
Does 7172839405 contain 12345? true
Does 9495929193 contain 12345? true

Determining if a given string of words has words greater than 5 letters long

So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒     You might want to use: +=
⇒     You might want to use: ==
⇒     You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)

How to get same index value from other array?

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)));
}

To ge the part of the String and Compare witha a variable(String Variable)

I have the String like:
String value = "13,14,15,16,17"
But i Dont know how many numbers are there with comma separation.
I want to compare with the variable say:
String varValue = "16"
It may be in any postion..
I want to compare these two string variables....
Please can anyone help?
You can do this sort of thing:
String values = '13,14,15,16,17'
String required = '16'
values.tokenize( ',' ).with { toks ->
println "There are ${toks.size()} elements in the list"
println "The list contains $required is ${toks.contains( required )}"
println "It is at position ${toks.indexOf( required )}"
}
Which prints
There are 5 elements in the list
The list contains 16 is true
It is at position 3
Use the split method to put the numbers in an array and then compare.
Here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Do not quite understand your question.
Dont know how many numbers are there with comma separation
use String method split()
I want to compare with the variable say: String varValue = "16"
use String method contains()
You can use the split method to receive an Array. Turning the Array into a List will allow you to use some helper functions such as contains and indexOf, which can be used to return whether the token exists or the position of the token.
String value = "13,14,15,16,17";
//Checks existence
boolean contains = Arrays.asList(value.split(",")).contains("16");
//Returns position
int pos = Arrays.asList(value.split(",")).indexOf("16") + value.split(",").length + 1;
These examples all use Java.
If you are using Java , then following can be done to achieve this :
1. Split the input string into an array.
2. convert that array into a list .
Now
a) To find total elements separated by comma , Use :
size().
b) To find if the list contains required element or not , Use :
contains().
c) To find position of element in list , Use :
indexof()
So the code will look like :
import java.util.Arrays;
import java.util.List;
public class Test{
public static void main(String[] args) {
String inputString = "13,14,15,16,17";
String element = "16";
// Convert the string into array.
String values[] = inputString.split(",");
// Create a list using array elements.
List<String> valList = Arrays.asList(values);
System.out.println("Size :" + valList.size());
System.out.println("List contains 5 " + valList.contains(element));
System.out.println("Position of element" + valList.indexOf(element));
}
}

Categories