Search code examples
javaandroidif-statementarraylistremove-if

ArrayList remove except if contains character


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".


Solution

  • 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());