0

I am trying to sort an ArrayList of strings. So far I have tried using ArrayList.sort but I am note sure how to use it properly.

My class looks like this:

     ArrayList<String> arraylist = new ArrayList<>();
        String value,value1,value2;
        value="String1";
        value1="String2";
        value3="String3";

        arraylist.add(value);
        arraylist.add(value1);
        arraylist.add(value2);

I have no idea how to sort this one. Last time when I was using ArrayList of custom objects like

ArrayList<myObject> = new ArrayList<>();

I implemented Comparable interface, then I overrode the compareTo method in myObject class and everything was...easier.

How do I sort with ArrayList using just simple Strings?

@Edit Trying few things on my own, I've used arraylist.sort(null) and somehow it worked like it was supposed to. No more help is needed, thank you guys.

2
  • What is your expected output? Commented Nov 18, 2016 at 18:03
  • Well, thats wasnt good example. Lets make value=b,value1=a,value2=aa, and I'd like to see a,aa,b Commented Nov 18, 2016 at 18:05

1 Answer 1

0

The sort() of ArrayList only works if you are proving a Comparator.

For the String Double Integer you can use Collection.sort(). It directly modifies the arraylist you pass instead of returning a new arraylist.

Code:

public static void main(String[] args) 
    {

        ArrayList<String> arraylist = new ArrayList<>();
        String value,value1,value2;
        value="C";
        value1="Z";
        value2="A";

        arraylist.add(value);
        arraylist.add(value1);
        arraylist.add(value2);
        System.out.println(arraylist);
        Collections.sort(arraylist);
        System.out.println(arraylist);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Tried this one in a first place since ArrayList.sort didn't work for me and all I've got was "Method call expected"
@BednarQ It's working fine for me. Can you please provide your whole code with Collections.sort()? With your imports,class,main().
I've tried arrayList.sort(null) and somehow it worked like it was expected to, so I think i dont need more help. Thank you anyway

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.