Results 1 to 6 of 6
  1. #1
    Propinquity is offline Member
    Join Date
    Oct 2013
    Posts
    63
    Rep Power
    0

    Default How do you sort an ArrayList by an object field WITHOUT using compareTo methods?

    I have a project where I must sort a collection of songs by a number of fields: year, rank, title and artist.
    in the project, we must use certain methods and we cannot add others without getting marked down.
    Here are the specific requirements:

    Sorting
    The -sortBy option will cause the output to be sorted by a particular field. If this option is specified, the output should be ordered according to the field named. If there are ties, the tied songs should appear in same order in which they were in the input file. If no -sortBy option is specified, the output should maintain the order of the input file.

    • public void sortYear()
      Order the songs in this collection by year (ascending).
    • public void sortRank()
      Order the songs in this collection by rank (ascending).
    • public void sortArtist()
      Order the songs in this collection lexicographically by artist (ascending, case-insensitive).
    • public void sortTitle()
      Order the songs in this collection lexicographically by title (ascending, case-insensitive).



    Here is the relevant code:

    SongCollection Class
    Java Code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.*;
    
    public class SongCollection {
    	ArrayList<Song> songs2;
    	ArrayList<Song> itemsToRemove = new ArrayList<Song>(); // second collection
    															// for items to
    															// remove
    
    	public SongCollection(ArrayList<Song> songs) { // constructor for
    													// SongCollection
    		this.songs2 = songs;
    	}
    
    	public void filterYear(Range r) {
    		for (Song song1 : songs2) {
    			if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())){
    				itemsToRemove.add(song1);
    		}
    	}
    		songs2.removeAll(itemsToRemove);
    		itemsToRemove.clear();
    }
    
    	public void filterRank(Range r) {
    		for (Song song1 : songs2) {
    			if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())){
    				itemsToRemove.add(song1);
    			}
    		}
    		songs2.removeAll(itemsToRemove);
    		itemsToRemove.clear();
    }
    
    	public void filterArtist(String s) {
    		for (Song song1 : songs2) {
    			if ((!(((song1.artist).equals(s))))){
    				itemsToRemove.add(song1);
    		}
    	}
    		songs2.removeAll(itemsToRemove);
    		itemsToRemove.clear();
    }
    	public void filterTitle(String s) {
    		for (Song song1 : songs2) {
    			if ((!(((song1.title).equals(s))))){
    				itemsToRemove.add(song1);
    		}
    	}
    		songs2.removeAll(itemsToRemove);
    		itemsToRemove.clear();
    }
    	public void sortTitle() {
    		
    	}
    
    	public void sortRank() {
    
    	}
    
    	public void sortArtist() {
    
    	}
    
    	public void sortYear() {
    
    	}
    
    	public String toString() {
    		String result = "";
    		for (int i = 0; i < songs2.size(); i++) {
    			result += " " + songs2.get(i);
    		}
    
    		return result;
    
    	}
    
    }
    Song Class
    Java Code:
    import java.util.Scanner;
    import java.util.StringTokenizer;
    
    public class Song  {
    	public int year;
    	public int rank;
    	public String artist;
    	public String title;
    
    	public static Song parse(String s) {
    		Song instance = new Song();
    		StringTokenizer tokenizer = new StringTokenizer(s, "\t");
    		instance.year = Integer.parseInt(tokenizer.nextToken());
    		instance.rank = Integer.parseInt(tokenizer.nextToken());
    		instance.artist = (tokenizer.nextToken());
    		instance.title = (tokenizer.nextToken());
    		return instance;
    	}
    
    	public int getYear() {
    		return year;
    	}
    
    	public int getRank() {
    		return rank;
    	}
    
    	public String getArtist() {
    		return artist;
    	}
    
    	public String getTitle() {
    		return title;
    	}
    
    	public String toString() {
    		String output = "\n\nYear = " + year + "\nRank = " + rank + "\nArtist = "
    				+ artist + "\nTitle = " + title;
    		return output;
    	}
    }
    Range Class
    Java Code:
    import java.util.StringTokenizer;
    
    public class Range {
    	private int min;
    	private int max;
    
    	public Range() {
    		System.out.println("Please wait.");
    	}
    
    	public static Range parse(String s) {
    		Range instance = new Range();
    		StringTokenizer tokenizer = new StringTokenizer(s, "-");
    		if (s.contains("-")) {
    			instance.min = Integer.parseInt(tokenizer.nextToken());
    			instance.max = Integer.parseInt(tokenizer.nextToken());
    
    		} else if (!(s.contains("-"))) {
    			{
    				instance.min = Integer.parseInt(s);
    				instance.max = Integer.parseInt(s);
    			}
    		}
    		return instance;
    	}
    
    	public boolean contains(int n) {
    		if (n > min && n < max) {
    			return true;
    		} else if (n == min && n == max) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	public int getMin() {
    		return min;
    	}
    
    	public int getMax() {
    		return max;
    	}
    }

  2. #2
    AlexGraal is offline Señor Member
    Join Date
    Jan 2014
    Posts
    184
    Rep Power
    0

    Default Re: How do you sort an ArrayList by an object field WITHOUT using compareTo methods?

    Well, just to throw an idea at you, here is part of a dumbed down version of a compression algorithm:
    Java Code:
    public static Comparator<freqComb> freqComparator = new Comparator<freqComb>(){  
            @Override
            public int compare(freqComb c1, freqComb c2) {
                return (c1.getFreq() - c2.getFreq());
            }
        };
      public static void treeBuild(PriorityQueue<freqComb> pQue) {
        while(pQue.size() > 1) {
          freqComb a = pQue.poll();
          freqComb b = pQue.poll();
          TreeNode temp = new TreeNode(a.getFreq() + b.getFreq(), "*", new TreeNode(a.getFreq(), (String) a.getChunk(), a.getTreeNode().getLeft(), a.getTreeNode().getRight()), new TreeNode(b.getFreq(), (String) b.getChunk(), b.getTreeNode().getLeft(), b.getTreeNode().getRight()));
          pQue.add(new freqComb(a.getFreq() + b.getFreq(), "*", temp));
        }
        root = pQue.poll().getTreeNode();
      }
    While all of the getFreq and getTreeNode stuff doesn't really help you much, the way I did the sorting here might.

    For this algorithm, I needed to sort data, then do something with it, and be able to add data in while doing something and have it be resorted.

    Since I stored my information in a custom class, I couldn't use a default sorting method, so I had to create my own custom comparator.

    If the comparator returns a negative value, then the first object is "smaller" (however you want to consider smaller). If it returns a positive value, the first object is "bigger," and if it is 0, then they are equal.

    This may not be what you need, but it might help - and I think there is a command to turn the priority que into an array after the sorting is done.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,930
    Rep Power
    5

    Default Re: How do you sort an ArrayList by an object field WITHOUT using compareTo methods?

    A word of warning on implementing Comparable or Comparator interfaces. IMHO, it is better to compare and return discrete values of -1, 0, and 1 rather than the difference. For example: In comparing a to b:

    Java Code:
    int a, b;
    
    // requires you to be certain of the magnitude of your data.
    return a - b; // instead of doing this (which won't always work)
    
    // do this :  My preference as it is straight forward
    if ( a < b) {
       return -1;
    }
    if (a > b) {
       return 1;
    }
    return 0;
    
    // you can also do this but there is really no point.
    return (a < b) ? -1 : ((a > b) ? 1 : 0);
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    Propinquity is offline Member
    Join Date
    Oct 2013
    Posts
    63
    Rep Power
    0

    Default Re: How do you sort an ArrayList by an object field WITHOUT using compareTo methods?

    Okay, thank you. I will try writing the sort methods with this information.

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,930
    Rep Power
    5

    Default Re: How do you sort an ArrayList by an object field WITHOUT using compareTo methods?

    BTW, I'm not certain that my answer helped you with the actual question. Are you required to write your own sort routine? All the compare type interfaces do is separate the comparison from the actual sorting code. Depending on what your instructor wants, you could just sort the List in each method given, focusing only on that particular field. I find it strange to restrict using additional home grown methods to help facilitate doing the programming exercises.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  6. #6
    Propinquity is offline Member
    Join Date
    Oct 2013
    Posts
    63
    Rep Power
    0

    Default Re: How do you sort an ArrayList by an object field WITHOUT using compareTo methods?

    Quote Originally Posted by jim829 View Post
    BTW, I'm not certain that my answer helped you with the actual question. Are you required to write your own sort routine? All the compare type interfaces do is separate the comparison from the actual sorting code. Depending on what your instructor wants, you could just sort the List in each method given, focusing only on that particular field. I find it strange to restrict using additional home grown methods to help facilitate doing the programming exercises.

    Regards,
    Jim
    Actually, I read the instructions again after reading your post, and it states
    "The remaining classes should include the following methods, along with any other methods or fields you find necessary or useful."
    So I guess I'm actually not as restricted as I thought!

Similar Threads

  1. Replies: 11
    Last Post: 01-27-2012, 11:32 PM
  2. Problem implementing compareTo for Arrays.sort
    By FallenBlade in forum New To Java
    Replies: 10
    Last Post: 11-07-2011, 08:08 PM
  3. Sort with CompareTo
    By ScienceLife in forum New To Java
    Replies: 7
    Last Post: 12-01-2010, 02:08 PM
  4. ArrayList Object Field
    By murph in forum New To Java
    Replies: 7
    Last Post: 08-23-2010, 09:25 AM
  5. Using Merge Sort to sort an ArrayList of Strings
    By coldfire in forum New To Java
    Replies: 3
    Last Post: 03-13-2009, 02:03 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •