0

Android Studio - Java

How can I remove all entries from an ArrayList except the ones that contain certain characters independently from upper and lower case?

String[] numbers = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve"};

ArrayList arrayList=new ArrayList<>(Arrays.asList(numbers));


ArrayList.remove();

E.g. if I choose the letters "Ne" I would like to remove all the entries from the arraylist except the entries containing the charachter string "ne".

LoveCoding
  • 79
  • 2
  • 13

5 Answers5

4

In android ,for non java-8

1.) Traverse you array values

2.) Apply toLowerCase() to convert value to lowercase and Check if it contains ne , if no then remove the element from list

for (String s: numbers) {
    if (!s.toLowerCase().contains("ne")) {
        arrayList.remove(s);
    }
}

list elements

One
Nine

Java 8

1.) Never use Raw type

2.) Apply the above logic in filter

ArrayList<String> arrayList=new ArrayList<>(Arrays.asList(numbers));
List<String> non_ne = arrayList.stream()
                    .filter(x->!x.toLowerCase().contains("ne"))
                    .collect(Collectors.toList());
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
2

You can use a stream

arrayList.stream().filter(x -> x.indexOf("ne") !=-1).collect(Collectors.toList());
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
2

Looking at your code I am thinking you are probably better off not adding them in the first place. you are effectively saying:

String[] numbers = new String[] {"One", "Two", "Three", ...}; //array
List list = Arrays.asList(numbers) //create a list
ArrayList arrayList = new ArrayList<>(list); //create an ArrayList

//remove those not matching from the ArrayList

I would prefer the approach of only adding the ones I need to be in the list:

List<String> list = new ArrayList<>(); //a LinkedList may be more appropriate 
for (String number : numbers) {
    if (number.toLowerCase().contains("ne")) {
        list.add(number );
    }
}
MartinByers
  • 1,240
  • 1
  • 9
  • 15
  • This is certainly helpful in other cases, however it doesn't really solve my problem. Thank you anyway for your help! – LoveCoding Jun 10 '17 at 12:30
1
List <String> filtered = arrayList.stream().filter(x -> x.contains("ne")).collect(Collectors.toList());
NiVeR
  • 9,644
  • 4
  • 30
  • 35
1

Try this:

Iterator<String> iter = arrayList.iterator();
while (iter.hasNext()) {
  String s = iter.next();
  if (s.toLowerCase().contains("ne")) iter.remove();
}
fdelafuente
  • 1,114
  • 1
  • 13
  • 24