sorting linked list in alphabetical order

185 Views Asked by At

I want to order nodes' chosen string variables. this is an homework due to tomorrow.

    public void sortSongName() {
        
        DefaultSongs sortedList = new DefaultSongs();
        
        int temp= Integer.MAX_VALUE;
        Song curr=root;
        Song hold = null;
        
        while(root.nextSong != null) {
            
            if(curr.getSongName().charAt(0)<hold.getSongName().charAt(0)) {
                hold=curr;
                curr=root.nextSong;
            }else {
                curr=root.nextSong;
            }
            
            sortedList.createSong(root.nextSong.getSongName(),root.nextSong.getBandName() , root.nextSong.getDuration());
            deleteSong(root.nextSong.getSongName());
            sortSongName();
        }
    }
2

There are 2 best solutions below

0
On

Assuming your song class look something like this

public class Song {
   private String name;

   public String name() {
       return name;
   }

   public void setName(final String name) {
       this.name = name;
   }
}

And the DefaultSongs class is just a repo with a list of Songs

public class DefaultSongs {

   private final List<Song> songList;

   public DefaultSongs() {
       this.songList = new ArrayList<>();
   }

   public List<Song> songList() {
       return songList;
   }
}

Simplest way would be to use java stream

public void sortSongsByName(){
    songList.stream().sorted(Comparator.comparing(Song::name));
}
0
On

The simplest way is to use Collections.sort(); For example:

 List<String> songs = Arrays.asList("Bam","Cam", "Am","Dam");
        Collections.sort(songs);
        System.out.println(songs);

This will give you the list in alphabetical order.