-3

ok. Rookie question.

I have a scanned string that i would like to sort using Collections.sort(string).

The string comes from a scanned file that has a bunch of "asdfasdfasdf" in it.

I have scanned the file (.txt) and the scannermethod returns a String called scannedBok;

The string is then added to an ArrayList called skapaArrayBok();

here is the code:

public ArrayList<String> skapaArrayBok() {

ArrayList<String> strengar = new ArrayList<String>();

strengar.add(scanner());
Collections.sort(strengar);

return (strengar);
}

in my humble rookie brain the output would be "aaadddfffsss" but no.

This is a schoolasigment and the whole purpose of the project is to find the 10 most frequent words in a book. But i can't get it to sort. But i just would like to know why it won't sort the scanned string?

4 Answers4

3

You are sorting the list, not the String. The list has only one element, so sorting it doesn't change anything.

In order to sort the content of the String, convert it to an array of characters, and sort the array.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Collections.sort() sorts the items in a list.

You have exactly one item in your list: the string "aaadddfffsss". There's nothing to sort.

SUGGESTIONS:

1) Read more strings into your collection

  public ArrayList<String> skapaArrayBok() {

    ArrayList<String> strengar = new ArrayList<String>();

    // Input three strings
    strengar.add(scanner());
    strengar.add(scanner());
    strengar.add(scanner());

    // Now sort
    Collections.sort(strengar);

... or ...

2) Split the string into characters, and sort the characters.

  public ArrayList<String> skapaArrayBok() {

    // Get string    
    String s = scanner());
    char[] charArray = s.toCharArray();
    Arrays.sort(charArray );

    // Return sorted string
    return (new String(charArray);
FoggyDay
  • 11,962
  • 4
  • 34
  • 48
0

It is correct to sort "strengar", the ArrayList. However, it would not change the ordering of the ArrayList if you've only added one String to it. A list with one element is already sorted. If you want to sort the ArrayList, you should call add() on the ArrayList with each String you need to add, then sort.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
0

You want to sort the characters within the String which is completely different and you need to re-organize the characters, a possible solution (especially knowing that Strings are immutable) is the following Sort a single String in Java

Community
  • 1
  • 1
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • The type `String` implements `Comparable` so it has a natural ordering. So `Collections.sort(List)` will sort the items in the `List` by the natural order of the String content, not by reference. Delete point one from your answer and I'll remove the downvote. – Bobulous Aug 06 '14 at 18:43