Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java – return an array of objects sorted by priority

getPriorityNotes[] returns an array with all PriorityNote objects. The notes must be sorted so that notes with priority 1 come first, then notes with priority 2 and lastly notes with priority 3.
This is what I have done so far:

public PriorityNote[] getPriorityNote()
  {
    PriorityNote[] arrayPriorityNote = notes.toArray(new PriorityNote[0]);

    //High = 1, low = 3
    int highest = arrayPriorityNote[0].getPriority();

    for (int i = 0; i < arrayPriorityNote.length; i++)
    {
      if (arrayPriorityNote[i].getPriority() < highest)
        highest = arrayPriorityNote[i].getPriority();
    }

    return arrayPriorityNote;
  }

Priority Note class:

public class PriorityNote extends Note
{
  private int priority;

  public PriorityNote(String message, int priority)
  {
    super(message);
    this.priority = priority;
  }

  public int getPriority()
  {
    return priority;
  }
  public Note copy()
  {
    return new PriorityNote(super.getMessage(), priority).copy();
  }
  public String toString()
  {
    return "Priority: " + priority + " " + super.toString();
  }
}

Note class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public abstract class Note
{
  private String message;

  public Note(String message)
  {
    this.message = message;
  }
  public String getMessage()
  {
    return message;
  }
  public abstract Note copy();

  public String toString()
  {
    return "Message: " + message;
  }
}

I’m a beginner so if somethings wrong let me know, thanks in advance.

>Solution :

You can do it as simple as the following:

public PriorityNote[] getPriorityNote(){
  Arrays.sort(arrayPriorityNote, Comparator.comparing(PriorityNote::getPriority));
  return arrayPriorityNote;
}

This uses Arrays.sort() method, which receives the array, and the Comparator that defines how to compare the objects.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading