creates new ArrayList with the strings in list that are shorter than int length

Im trying to figure out how to write this as Im new to coding and we just started ArrayLists in class.

Im trying to write a method called getShorterThan that recieves an ArrayList of Strings “List” and an integer “Length” and returns a new ArrayList with the strings in the list whose length is shorter than int “Length”.

Im also supposed to use “length()” for the string size.

This isn’t a project just an example to try in our notes but Im not sure how to do this, if someone can explain this to me it’d be wonderful!

Comments 2

  • The way I would do this is I would create a loop to go through each String in the ArrayList and test each one against int Length. One way to do this would be to first create an empty ArrayList and use a for loop to check if List.get(index).length() < Length, then use the .add() method to add the String to the new ArrayList.

  • You can use substring.

    public static ArrayList<String> getShorterThan(ArrayList<String> List, int Length) {
          ArrayList<String> s = new ArrayList<>();
          for (String let : List) {
                if (let.length() > Length) {
                } else {
          return s;


电子邮件地址不会被公开。 必填项已用*标注