How can I create a List with sorted Strings and a specific Integer in Java?

Hay there, I need to create a list for a project with amount of terms for this method but it kind of didn’t work as I thought. The “term”-names also have to look like this and have been sorted in the form of “Term:1”, “Term:2”,…, “Term:amount”. If amount should be negative I have to return an empty list. I tried the following:

public static List <String> createTerms(int amount){
List <String> termNames = new ArrayList<String>();
    if (amount>0){
        termNames.add(amount,"Term:"+amount);
        Collections.sort(termNames);
        return termNames;
    }else
        return Collections.emptyList();
}

Answer

Even though this is tagged as JavaScript, this looks like Java. Take a look at the ArrayList documentation. Here is the method for add():

add(int index, E element)

Where it adds element to the structure at index. So it doesn’t work the way you assumed in your code. If you would like to use ArrayList, even though I would advise against and suggest you use something like Map, found here, I would suggest you use a for-loop to add the terms in. So instead of:

 termNames.add(amount,"Term:");
 Collections.sort(termNames);

You can just do:

  if (amount > 0){
      for (int i = 0; i < amount; i++) {
          String element = "Term: " + (i + 1);
          termNames.add(element);
      } 
      return termNames;
  }

Also, I am a bit confused about your logic. Shouldn’t the prompt be that you should return an empty list if amount < 0? Can you clarify a bit if my answer doesn’t answer your question?

Leave a Reply

Your email address will not be published. Required fields are marked *