2

I am having trouble implementing a comparator into my program.

This program was originally written as an example of how to create a menu using swing. The program simply displays a menu, sub menu and a list of movies with their title, date, and studio. A larger array stores each movie, in its own array, with its title, date and studio.

Now, I have to find a way to sort these strings using a comparator. Something like this:

Arrays.sort(data, new Comparator<String[]>() {

        public int compare(final String[] entry1, final String[] entry2) {
            final String field1 = entry1[0];
            final String field22 = entry2[0];
            return field1.compareTo(field2);
        }
    });

Problem is, I have never used a comparator, nor am I sure on how to implement it.

I have added the source code for the original program below.

Any and all help will be greatly appreciated.

Thank you.

Edit This program is similar to a program from a Java textbook, but we are specifically told not to solve the sort in the fashion the textbook does.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

 class MenuExample extends Frame implements ActionListener
 {
     MenuBar mbar;
     Menu menu,submenu;
     MenuItem m1,m2,m3,m4,m5;

     public MenuExample ()
    {
         String[][] data = new String[][]
         {
             new String[] { "Casablanca", "Warner Brothers", "1942" },
             new String[] { "Citizen Kane", "RKO Pictures", "1941" },
             new String[] { "Singin' in the Rain", "MGM", "1952" },
             new String[] { "The Wizard of OZ", "MGM", "1930"}
         };

        // Set frame properties
        setTitle("AWT Menu"); // Set the title
        setSize(800,500); // Set size to the frame
        setLayout(new FlowLayout()); // Set the layout
        setVisible(true); // Make the frame visible
        setLocationRelativeTo(null);  // Center the frame

        // Create the menu bar
        mbar=new MenuBar();

        // Create the menu
        menu=new Menu("Menu");

        // Create the submenu
        submenu=new Menu("Sub Menu");

        // Create MenuItems
        m1=new MenuItem("Menu Item 1");
        m2=new MenuItem("Menu Item 2");
        m3=new MenuItem("Menu Item 3");

        m4=new MenuItem("Menu Item 4");
        m5=new MenuItem("Menu Item 5");
        m1.addActionListener(this);

        // Attach menu items to menu
        menu.add(m1);
        menu.add(m2);
        menu.add(m3);

        // Attach menu items to submenu
        submenu.add(m4);
        submenu.add(m5);

        // Attach submenu to menu
        menu.add(submenu);

        // Attach menu to menu bar
        mbar.add(menu);

        // Set menu bar to the frame
        setMenuBar(mbar);


        JPanel textPanel = new JPanel();

        JTextPane textArea = new JTextPane();


        Dimension textAreaDimensions = new Dimension(100, 300);
        textArea.setPreferredSize(textAreaDimensions);

        //width: 770 height: 1000
        JScrollPane scroll = new JScrollPane (textArea,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        Document doc=textArea.getDocument();
        try
        {
            for(int i=0;i<4;i++)
            {
                for(int j=0;j<3;j++)
                doc.insertString(doc.getLength(),data[i][j]+"\t",
                textArea.getStyle("bold"));
                doc.insertString(doc.getLength(),"\n",
                textArea.getStyle("bold"));
            }//end for

        }//end try

        catch (Exception e) {}
        textPanel.add(scroll);
        add(textPanel);
        validate();
        repaint();
    }//end MenuExample

    public static void main(String args[])
    {
        new MenuExample();
    }//end main

    public void actionPerformed(ActionEvent e)
    {
        System.out.println(e.getActionCommand());
    }//end actionPerformed
}//end class
7
  • What type of sorting order you want to use? Commented Apr 9, 2015 at 3:35
  • your intention is not clear. Do you want to sort individual String arrays? or something else? Commented Apr 9, 2015 at 3:45
  • That is a question I had myself. It was not specified, but I am sure it should be by title, studio or year. Maybe alphabetically as well? Commented Apr 9, 2015 at 3:45
  • My intention isn't clear because the specifications for the sort were VERY vague. I was just told to sort the array using a comparator. Sorry that I cannot give more information as to how Commented Apr 9, 2015 at 3:46
  • 1
    @ebonymessiah: If Daniel Nugent's post helped or solved your problem then mark his post as accepted or as best answer. Commented Apr 9, 2015 at 4:32

2 Answers 2

2

I just put together this simple example to show two different ways of using a Comparator:

import java.util.Arrays;
import java.util.Comparator;

public class ArraySort
{
  public static void main(String[] args)
  {
     String[][] data = new String[][]
         {
             new String[] { "Casablanca", "Warner Brothers", "1942" },
             new String[] { "Citizen Kane", "RKO Pictures", "1941" },
             new String[] { "Singin' in the Rain", "MGM", "1952" },
             new String[] { "The Wizard of OZ", "MGM", "1930"},
             new String[] { "AaaaaThe Wizard of OZ", "MGM", "1943"}
         };

     Arrays.sort(data, new Comparator<String[]>() {

        @Override
        public int compare(final String[] entry1, final String[] entry2) {
            final String field1 = entry1[0];
            final String field2 = entry2[0];
            return field1.compareTo(field2);
        }
     });

     print(data);

     System.out.println();

     Arrays.sort(data, new SortByDate());

     print(data);

     System.out.println();

     Arrays.sort(data, new SortByCompany());

     print(data);
  }

  public static void print(String[][] data){
    for (String[] array : data){
      for (String s : array){
        System.out.print(s + " ");
      }
      System.out.println();
    } 
  }

}

public class SortByDate implements Comparator<String[]>{
  @Override
  public int compare(final String[] entry1, final String[] entry2) {
    final String field1 = entry1[2];
    final String field2 = entry2[2];
    return field1.compareTo(field2);
  }
}

public class SortByCompany implements Comparator<String[]>{
  @Override
  public int compare(final String[] entry1, final String[] entry2) {
    final String field1 = entry1[1];
    final String field2 = entry2[1];
    return field1.compareTo(field2);
  }
}

Output:

AaaaaThe Wizard of OZ MGM 1943 
Casablanca Warner Brothers 1942 
Citizen Kane RKO Pictures 1941 
Singin' in the Rain MGM 1952 
The Wizard of OZ MGM 1930 

The Wizard of OZ MGM 1930 
Citizen Kane RKO Pictures 1941 
Casablanca Warner Brothers 1942 
AaaaaThe Wizard of OZ MGM 1943 
Singin' in the Rain MGM 1952 

The Wizard of OZ MGM 1930 
AaaaaThe Wizard of OZ MGM 1943 
Singin' in the Rain MGM 1952 
Citizen Kane RKO Pictures 1941 
Casablanca Warner Brothers 1942  
Sign up to request clarification or add additional context in comments.

Comments

1

Looking at the docs of Comparator, you will notice that it's a Java interface, which means you can create a class that implements both the Comparator.compare(T o1, T o2) and Comparator.equals(Object obj) methods.

So suppose you encapsulate all your string attributes in a Movie object (which I highly recommend), you can implement a MovieNameComparator class like this:

public class MovieNameComparator implements Comparator<Movie> {
  @override  
  public int compare(Movie m1, Movie2) {
    return m1.getName().compareToIgnoreCase(m2.getName());
  }

  @override
  public boolean equals(Movie otherMovie) {
    return this.getName().equals(otherMovie.getName());
  }
}

Now, you can use this comparator to sort your array of movies by the movie name using something like this:

Arrays.sort(data, new MovieNameComparator());

If you want to sort by other movie attributes, you can follow the same approach and create more comparator classes, like MovieDateComparator, MovieProductionStudioComparator etc.

UPDATES: As per requested, a Movie class can look something like:

public class Movie{
  private String name;
  private String studio;
  private Date releaseDate;

  // add getters and setters here...
}

3 Comments

What exactly do you mean by "Encapsulating all your string attributes in a Movie object"? isn't all the string data already in my data object?
Create a class name Movie, and defined all the attributes there. I have included an example in my answer.
@ebonymessiah Please consider upvoting my answer if you liked it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.