Search code examples
javastringarrayliststringbuilder

How to remove the StringBuilder object from an ArrayList?


I am trying to remove the StringBuilder object from an ArrayList, but I'm unable to do that. If I pass this line al.remove("haiti"); that's a string object and is not equals to the StringBuilder and it returns to false. I tried with al.remove(new StringBuilder("haiti")), but that doesn't work as well. Can anyone help?

import java.util.*;

public class HelloWorld {
    public static void main(String[] args) {
        List<StringBuilder> al = new ArrayList<>();
        al.add(new StringBuilder("3")); // [3]
        al.add(new StringBuilder("haiti")); // [3, haiti]
        System.out.println(al); // [3, haiti]
        System.out.println(al.remove(new StringBuilder("haiti")));
        // false, but I want true XD

        System.out.println(al); // Actual [3, haiti], Expected: [3]
    }
}

Solution

  • Since Java 8 you can use removeIf method:

    List<StringBuilder> al = new ArrayList<>();
    al.add(new StringBuilder("3"));
    al.add(new StringBuilder("haiti"));
    
    System.out.println(al); // [3, haiti]
    // if the string contained in StringBuilder is equal to the
    // desired string, then remove this element from the list
    System.out.println(al.removeIf(sb -> sb.toString().equals("haiti"))); // true
    System.out.println(al); // [3]
    

    See also: How to use StringBuilder inside the reduce method in java 1.8?