Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Sorting an array by date/time

Posted on 2004-07-31
13
784 Views
Last Modified: 2012-05-05
I'm fairly new to Java, so I'll try and explain what I need properly.

I've got a frame, which reads a text containing log entries.  However, the log entries will not be in any kind of order, but when I display them, I'd like them to be in date/time order.

An example entry would be:-

31/07/2004-10:00-Log entry.
15/07/2004-09:00-Another log entry.

So, how can I display those entries (note the log file could contain an infinate number of entries) in a list box in my frame? You may need to supply all of the code for the frame/file reading bit - although I can do it myself, it could cause problems inserting code into the mess I've already created!

Finally, this will be inside another program, so I already have a main function. The screen will be called from other methods in other java files.

Hope I've explained it properly. If not, just let me know.

Thanks,

Adrian Johnson
0
Comment
Question by:adrianjohnson
  • 4
  • 4
  • 3
  • +1
13 Comments
 
LVL 92

Expert Comment

by:objects
ID: 11683246
Use Arrays.sort() method to sort your array, using a custom Comparator that does the date/time comparison (or Collections.sort() if in a collection)
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 200 total points
ID: 11683467
You need to parse your file into classes that can be made into entries in a List model. Run this - the entries have been hard-coded. You will supply yours from file:

import java.text.SimpleDateFormat;
import java.util.Date;

public class LogEntry implements Comparable {
      private final static String DATE_FORMAT_STRING = "dd/MM/yyyy-HH:mm";
      private final static int DATE_PARSE_OFFSET = 16;
      private String datePart;
      private String entry;
      private Date date;
      private SimpleDateFormat format;

      public LogEntry(String entry) {
            format = new SimpleDateFormat(DATE_FORMAT_STRING);
            parse(entry);
      }

      public void setDatePart(String datePart) {
            this.datePart = datePart;
      }

      public String getDatePart() {
            return datePart;
      }

      public void setEntry(String entry) {
            this.entry = entry;
      }

      public String getEntry() {
            return entry;
      }

      public Date getDate() {
            return date;
      }

      public String toString() {
            return entry;
            // or the following for just the date
            //return datePart;
      }

      private void parse(String entry) {
            this.entry = entry;
            datePart = entry.substring(0, DATE_PARSE_OFFSET);
            try {
                  date      = format.parse(datePart.trim());
            }
            catch(Exception e) {
                  e.printStackTrace();
                  System.out.println("Date part is: " + datePart);
            }
      }

      public int compareTo(Object other) {
            LogEntry otherEntry = (LogEntry)other;
            return date.compareTo(otherEntry.getDate());
      }

      // TESTING PURPOSES ONLY!
      public static void main(String[] args) {

            String entry1 = "31/07/2004-10:00-Log entry";
            String entry2 = "15/07/2004-09:00-Another log entry";
            String entry3 = "15/07/2004-08:15-Another log entry from earlier the same day";

            java.util.Vector v = new java.util.Vector();
            v.add(new LogEntry(entry1));
            v.add(new LogEntry(entry2));
            v.add(new LogEntry(entry3));

            java.util.Collections.sort(v);
            System.out.println(v);

            javax.swing.JFrame frame = new javax.swing.JFrame();
            frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
            javax.swing.DefaultComboBoxModel model = new javax.swing.DefaultComboBoxModel(v);
            javax.swing.JList list = new javax.swing.JList(model);
            frame.getContentPane().add(list, java.awt.BorderLayout.CENTER);
            frame.setSize(100, 100);
            frame.setVisible(true);

      }

}
0
 

Author Comment

by:adrianjohnson
ID: 11684376
Thanks for the entries so far. I'm a little busy at the moment, but will try them and see what happens.

Adrian Johnson
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 30

Expert Comment

by:Mayank S
ID: 11687579
0
 

Author Comment

by:adrianjohnson
ID: 11706822
I'm working through your code, CEHJ, and changed the name of the main function to DisplayLog.  Having problems calling it, though, from another class:

LogEntry logscreen = new LogEntry();
logscreen.DisplayLog();

The error I get is "The contructor LogEntry is undefined". Is it something I'm missing/doing wrong? It's probably my understanding (it's very hot here in the UK, and I can't concentrate!).

Thanks,

Adrian Johnson
0
 
LVL 92

Expert Comment

by:objects
ID: 11710579
try:

LogEntry.DisplayLog();

You can sort your entries with or without using a seperate class to represent an entry.
The key is using the sort() method and providing a method to handle xomparing two entries.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11712838
If you have provided a parameterized constructor in the LogEntry class, then you will need to give a default constructor (with no parameters) too, otherwise you cannot instantiate it without arguments, like:

LogEntry logscreen = new LogEntry () ;

If the DisplayLog () method is still static, you don't need an object for calling it and you can do it directly using the class-name, like objects has shown.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11712848
objects, are you still listening to: http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21080150.html ?

CEHJ, can I have some inputs from you on that one please, if you want to say something?
0
 

Author Comment

by:adrianjohnson
ID: 11713669
Now I'm getting confused, as it appears I'm getting two different methods of calling the class (and neither of them work).  I renamed the main function DisplayLog(), so it looks like:

public void DisplayLog() {

          String entry1 = "31/07/2004-10:00-Log entry";
          String entry2 = "15/07/2004-09:00-Another log entry";
          String entry3 = "15/07/2004-08:15-Another log entry from earlier the same day";

          java.util.Vector v = new java.util.Vector();
          v.add(new ScreenDisplay(entry1));
          v.add(new ScreenDisplay(entry2));
          v.add(new ScreenDisplay(entry3));

          java.util.Collections.sort(v);
          System.out.println(v);

          javax.swing.JFrame frame = new javax.swing.JFrame();
          frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
          javax.swing.DefaultComboBoxModel model = new javax.swing.DefaultComboBoxModel(v);
          javax.swing.JList list = new javax.swing.JList(model);
          frame.getContentPane().add(list, java.awt.BorderLayout.CENTER);
          frame.setSize(100, 100);
          frame.setVisible(true);

     }

How Do I call it from another function in another class?  If I use mayankealges code, I get "The Constructor LogEntry is undefined".  If I use objects code, I get "The method DisplayLog is not static".

Remember, I'm fairly new to Java (and baking hot here in the UK), so you need to be really specific.

Thanks,

Adrian Johnson
0
 
LVL 92

Assisted Solution

by:objects
objects earned 100 total points
ID: 11713683
> public void DisplayLog() {

make it static:

public static void DisplayLog() {
0
 

Author Comment

by:adrianjohnson
ID: 11713703
D'oh!

Thanks Objects.  Sorry I'm so dim, but that worked a treat!


Adrian Johnson
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11716067
8-)
0
 
LVL 92

Expert Comment

by:objects
ID: 11722332
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
HashTable highest marks enumeration alternative 9 43
jdbc error in jsp application 20 63
Java: The Public Class Main 4 30
ejb entity bean example 2 10
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question