How To Use Regex In String List? - java

I'm trying to use regex to find a pattern across a string list:
static List<Integer> getMatchingIndexes(List<String> list, String regex) {
ListIterator<String> li = list.listIterator();
List<Integer> indexes = new ArrayList<Integer>();
System.out.println(list.matches("\\w.*"));
while(li.hasNext()) {
int i = li.nextIndex();
String next = li.next();
if(Pattern.matches(regex, next)) {
indexes.add(i);
}
}
System.out.println(indexes);
return indexes;
}
It looks like nothing is showing up int he list, when I try to see if there are any matches (list.matches("\w.*")); (just an example, not the actual regex), it keeps giving me an error:
The method matches(String) is undefined for the type List
How can I use regex on this list?

Iterate through the list (using a for-each loop) and check for matches:
for (String s : list) {
s.matches("\\w.*");
// Do stuff here.
}

Try to iterate through each item in the List<Integer> by the following:
for(Integer i : indexes){
System.out.println(i.toString().matches("\\w.*"));
}
The above is equivalent to:
for(int i=0; i<indexes.size(); i++){
System.out.println(indexes.get(i).toString().matches("\\w.*"));
}

Related

Remove elements from ArrayList after finding element with specific char

I have an ArrayList that contains a number of Strings, I want to be able to iterate through the ArrayLists contents searching for a string containing a semicolon. When the semicolon is found I then want to delete all of the Strings including and after the semicolon string.
So;
this, is, an, arra;ylist, string
Would become:
this, is, an
I feel like this is a very simple thing to do but for some reason (probably tiredness) I can't figure out how to do it.
Here's my code so far
public String[] removeComments(String[] lineComponents)
{
ArrayList<String> list = new ArrayList<String>(Arrays.asList(lineComponents));
int index = 0;
int listLength = list.size();
for(String str : list)
{
if(str.contains(";"))
{
}
index++;
}
return lineComponents;
}
This becomes trivial with Java 9:
public String[] removeComments(String[] lineComponents) {
return Arrays.stream(lineComponents)
.takeWhile(s -> !s.contains(";"))
.toArray(String[]::new);
}
We simply form a Stream<String> from your String[] lineComponents and take elements until we find a semicolon. It automatically excludes the element with the semicolon and everything after it. Finally, we collect it to a String[].
First of all I think you are confusing arrays and arraylists. String[] is an array of strings while ArrayList<String> is an arraylist of strings. Take into account that those are not the same and you should read Array and ArrayList documentation if needed.
Then, to solve your problem following the ArrayList approach you can go as follows. Probably it's not the optimum way to do it but it will work.
public List<String> removeComments(List<String> lineComponents, CharSequence finding)
{
ArrayList<String> aux = new ArrayList<String>();
for(String str : lineComponents)
{
if(str.contains(finding))
break;
else
aux.add(str);
}
return aux;
}
This example is just for performance and bringing back my old favorite arraycopy:
public String[] removeComments(String[] lineComponents) {
int index = -1;
for (int i = 0; i < lineComponents.length; i++) {
if ( lineComponents[i].contains(";") ) {
index = i;
break;
}
}
if (index == -1) return lineComponents;
return Arrays.copyOf(lineComponents, index);
}

Remove String from list if certain character missing

I have a list of words ["home", "shop", "salmon", "time"] and I have a scrambled String "ahlowemr". I want to check if each word in the list has characters from this scrambled String and remove the word from list if it doesn't contain all the characters.
In this example, less "home", the remaining 3 Strings should be removed. I tried to loop as follows but it doesn't allow me to check characters. And I am nesting loops which I think is not a good idea. Is there any way around this?
ArrayList<String> myList = new ArrayList<String>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
for(String s : myList){
for(char c : scrambled.toCharArray()){
if(!s.contains(c)){ //doesn't allow character c
myList.remove(s);
}
}
}
If you want to remove items from a list while you iterate it, you should use an Iterator, also, the contains(...) method expects a String, not a char.
Here is what you can do:
for(Iterator<String> it = myList.iterator(); it.hasNext();){
String s = it.next();
for(char c : scrambled.toCharArray()){
if(!s.contains(String.valueOf(c))){
it.remove();
break;
}
}
}
ArrayList<String> myList = new ArrayList<String>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
for(int i = 0; i < myList.size(); i++) {
for(char c : scrambled.toCharArray()){
if(!myList.get(i).contains(c.toString())){ //doesn't allow character in that position
// There is a simple way using a regex or maybe a hashtable
myList.remove(s);
break; // break will jump into the next list value
}
}
}
java-8 solution for completeness:
ArrayList<String> myList = new ArrayList<>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
myList = myList.stream()
.filter(s -> scrambled.chars()
.allMatch(c -> s.contains(String.valueOf((char) c))))
.collect(Collectors.toCollection(ArrayList<String>::new));

Displaying group of elements in an Arraylist

i'm trying to display few elements of an arraylist if contition is true. The method gets String that should be found in arrayList. After that there are some other values that are contained after the line in List that has beed found.
I need to print thause line's out that would be 1_4_1334-Automatic.... I have tried to use Iterator but with no luck. It just seens that i just cannot get it.
So if am looking for 2210002_4_1294-Group i should get all strings that contain "Automatic" till 2210003_4_1295-Group is reached.
Any idea how it could be done ?
Thanks a lot :)
MyArrayList:
2210002_4_1294-Group
1_4_1334-Automatic
2_4_1336-Automatic
3_4_1338-Automatic
4_4_1340-Automatic
5_4_1342-Automatic
6_4_1344-Automatic
7_4_1346-Automatic
8_4_1348-Automatic
9_4_1350-Automatic
2210003_4_1295-Group
1_4_1378-Automatic
2_4_1380-Automatic
2210004_4_1296-Group
1_4_1384-Manual
2_4_1386-Manual
Method might look like this:
private void findValueInList(String group){
Iterator<String> iter = arrayList.iterator();
while(iter.hasNext()){
String name = iter.next();
if(name.equals(group)){
here i need to get ValueThatINeed
}
}
}
I guess your question is already answered Here
Simply iterate over your arraylist and check each value like the code below:
ArrayList<String> myList ...
String searchString = "someValue";
for (String curVal : myList){
if (curVal.contains(searchString)){
// The condition you are looking for is satisfied
}
}
I solved it like this:
private ArrayList<String> filterList(String nameToFind) {
ArrayList<String> elements = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(nameToFind)) {
while (list.get(i+1).contains("Manual") || list.get(i+1).contains("Automatic")) {
elements.add(list.get(i+1));
i++;
}
}
}
return elements;
}

Java equivalent for PHP preg_grep

Could somebody tell me if a Java equivalent exist for PHP preg_grep()? Or supply me with a good way to accomplish the same?
I need to do string matching against element in input array and return array with input array's indexes as preg_grep() does.
There is no exact equivalent. But you can use the String#matches(String) function to test if a string matches a given pattern. For example:
String s = "stackoverflow";
s.matches("stack.*flow"); // <- true
s.matches("rack.*blow"); // <- false
If you want a result array with the matching indices, you can loop over your given input array of strings, check for a match and add the current index of the loop to your result array.
You could use this kind of function, using String.matches() and iterating over your array :
public static List<Integer> preg_grep(String pattern, List<String> array)
{
List<Integer> indexes = new ArrayList<Integer>();
int index = 0;
for (String item : array) {
if (item.matches("ba.*")) {
indexes.add(index);
}
++index;
}
return indexes;
}
Ideone Example
How about something like:
private static String[] filterArrayElem(String[] inputArray) {
Pattern pattern = Pattern.compile("(^a.*)");
List<String> resultList = new ArrayList<>();
for (String inputStr : inputArray) {
Matcher m = pattern.matcher(inputStr);
if (m.find()) {
resultList.add(m.group(0));
}
}
return resultList.toArray(new String[0]);
}
You can then use it in the following way:
String [] input = { "apple", "banana", "apricot"};
String [] result = filterArrayElem(input);

How to remove items from generic arraylist in Android (Java)

I have a generic arraylist of an object here I want to remove certain elements, The problem is when I iterate the list with for loop, I can't do a simple sequence of remove()'s because the elements are shifted after each removal.
Thanks
Use Iterator to remove element
Like
Iterator itr = list.iterator();
String strElement = "";
while (itr.hasNext()) {
strElement = (String) itr.next();
if (strElement.equals("2")) {
itr.remove();
}
}
See here
You can iterate the list this way ...
public void clean(List<Kopek> kopeks) {
for(Kopek kopek : kopeks) {
if (kopek.isDirty())
kopeks.remove(kopek);
}
}
Which is equiv to ...
public void clean1(List<Kopek> kopeks) {
Iterator<Kopek> kopekIter = kopeks.iterator();
while (kopekIter.hasNext()) {
Kopek kopek = kopekIter.next();
if (kopek.isDirty())
kopeks.remove(kopek);
}
}
Don't do this ... (due to the reason you have already observed.)
public void clean(List<Kopek> kopeks) {
for(int i=0; i<kopeks.size(); i++) {
Kopek kopek = kopeks.get(i);
if (kopek.isDirty())
kopeks.remove(i);
}
}
However, I believe removal by index rather than by object is more efficient. Removal by object is not efficient because the list is in most cases not a hashed list.
kopeks.remove(kopek);
vs
kopeks.remove(i);
To achieve positional remove, by treating a moving target appropriately ...
public void clean(List<Kopek> kopeks) {
int i=0;
while(i<kopeks.size()) {
Kopek kopek = kopeks.get(i);
if (kopek.isDirty()) // no need to increment.
kopeks.remove(i);
else
i++;
}
}
If you have the objects that you want to remove from your ArrayList<T> you can use :
mArrayList.remove(object);
or you can use an Iterator to remove your objects:
while(iterator.hasNext()){
if(iterator.next() == some condition for removal){
iterator.remove();
}
}
You could iterate backwards and remove as you go through the ArrayList. This has the advantage of subsequent elements not needing to shift and is easier to program than moving forwards.
List<String> arr = new ArrayList<String>();
ListIterator<String> li = arr.listIterator(arr.size());
// Iterate in reverse.
while(li.hasPrevious()) {
String str=li.previous();
if(str.equals("A"))
{
li.remove();
}
}
Create a separate ArrayList of Index of the data to be removed from the original ArrayList, then remove those elements by looping over it with for loop.
ArrayList<Myobj> arr = new ArrayList<Myobj>();
for (Myobj o : arr){
arr.remove(arr.indexOf(o));
}
without using iterators also solves the issue.. All i wanted to do is get the index which are to be deleted and sort it in decending order then remove it from the list.
check the code below
Arraylist<obj> addlist = getlist();
List<Integer> indices = new ArrayList<Integer>();
for(int i=0; i<addlist.size() ;i++){
if(addlist.get(i).getDelete()){
indices.add(i);
}
}
Collections.sort(indices, Collections.reverseOrder());
for (int i : indices)
addlist.remove(i);

Categories