Home java How to sort TreeSet ascending and descending to Java

How to sort TreeSet ascending and descending to Java

Author

Date

Category

It is not possible to sort TreeSet one of the elements of the class
Here is what task looks like:

in the “A.CSV” file recorded a list of students who surrendered exams, indicating the surname, groups and marks. Information about each student
Stored in a separate line. Read information in a hosted list
(LinkedList). Create two collections like TreeSet. Elements TreeSet.
Are objects containing surname and middle score of the student. In the first
Collections of lists sort by increasing the middle score in
The second is descending. New collections Print on screen.

What did I manage to write at the moment (I tried using comparable):

import java.io. *;
Import java.util. *;
CLASS CAPITAL {
  String Name;
  String Group;
  ArrayList & LT; Integer & GT; Grade = New ArrayList & lt; & gt; ();
  Double SR;
}
Class ASD Implements Comparable & LT; ASD & GT; {
  String Fname;
  Double Midd;
  Public ASD (String FFName, Double MID) {
    fname = ffname;
    MIDD = MID;
  }
  Public int COMPARETO (ASD O) {
    Return Double.comPare (Midd, O.Midd);
  }
}
Public Class Main {
  Public Static Void Main (String [] Args) {
    STRING PATH = "A.CSV";
    String Line = "";
    LinkedList & LT; Capital & GT; List = New LinkedList & lt; & gt; ();
    TreeSet & LT; ASD & GT; Tree1 = New TreeSet & lt; & gt; ();
    TreeSet & LT; ASD & GT; Tree2 = New TreeSet & lt; & gt; ();
    Try {
      BufferedReader Br = New BufferedReader (NEW FILEREADER (PATH));
      While ((Line = Br.ReadLine ())! = NULL) {
        String [] Values ​​= Line.Split (",");
        Capital Ex = New Capital ();
        EX.NAME = VALUES [0];
        EX.Group = Values ​​[1];
        For (int i = 2; I & LT; (Values.Length - 1); I ++) {
          int num = integer.parseint (Values ​​[i]);
          EX.GRADE.ADD (NUM);
        }
        List.add (ex);
      }
    } Catch (IoException E) {
      E.PrintStackTrace ();
    }
    For (Capital S: List) {
      Double Sum = 0;
      For (int j = 0; j & lt; s.grade.size () - 1; j ++) {
        SUM + = S.GRADE.GET (J);
      }
      Double SRED = SUM / S.GRADE.SIZE ();
      S.SR = SRED;
      Tree1.add (NEW ASD (S.Name, S.SR));
      Tree2.add (NEW ASD (S.Name, S.SR));
    }
    For (ASD S: Tree1) {
      System.out.printLN (S.FNAME);
      System.out.PrintLN (S.Midd);
    }
  }
}

Example of data in the file:
Pavlov, NP02,3,5,2,4,3,5
Ivanov, NP3,5,4,5,3,5,2,4,5
Aksenov, NP02,4,5,3,4,2,4,5,5


Answer 1, Authority 100%

To sort TreeSet to specify the sorting order, which is defined either the object itself by improving the Comparable interface, or using the Comparator interface, which can be transmitted to the designer. The second method in this case is suitable better.
But this is not the main problem of your code. You violate the most fundamental principles, including the principles of the OOP. The code is unnecessary complex. In addition, you made a mistake in the FOR cycle (int i = 2; i & lt; (values.length – 1); I ++), where it was necessary to use for (int i = 2; i & lt; values.length; i ++), otherwise You will always miss the latest student assessment. Therefore, disassemble this solution and, if any questions arise, ask them in the comments:

import java.io.ioException;
Import java.nio.file.paths;
Import java.util.comparator;
Import java.util.linkedlist;
Import java.util.list;
Import java.util.scanner;
Import java.util.set;
Import java.util.treeset;
Import java.util.stream.intstream;
Import java.util.stream.streamsupport;
Public Class Main {
  Public Static Void Main (String [] Args) Throws IoException {
    STRING PATH = "A.CSV";
    List & lt; Capital & GT; List = ReadFromFile (Path);
    SET & LT; Capital & GT; Ordertreeset = New TreeSet & LT; & GT; (Capital.ComparingDouble (Capital :: getavg)); 
orderTreeSet.addAll (list);
    Set & lt; Capital & gt; reverseTreeSet = new TreeSet & lt; & gt; (Comparator.comparingDouble (Capital :: getAvg) .reversed ());
    reverseTreeSet.addAll (list);
    print (orderTreeSet);
    System.out.println ("********************************");
    print (reverseTreeSet);
  }
  private static List & lt; Capital & gt; readFromFile (String path) throws IOException {
    List & lt; Capital & gt; capitals = new LinkedList & lt; & gt; ();
    Scanner sc = new Scanner (Paths.get (path), "UTF-8");
    while (sc.hasNext ()) {
      String [] values ​​= sc.nextLine (). Split (",");
      Double average = IntStream.range (2, values.length)
          .map (i - & gt; Integer.valueOf (values ​​[i]))
          .average (). getAsDouble ();
      capitals.add (new Capital (values ​​[0], values ​​[1], average));
    }
    return capitals;
  }
  private static void print (Iterable args) {
    StreamSupport.stream (args.spliterator (), false) .forEach (System.out :: println);
  }
}
class Capital {
  private final String name;
  private final String group;
  private final Double avg;
  public Capital (String name, String group, Double avg) {
    this.name = name;
    this.group = group;
    this.avg = avg;
  }
  public String getName () {
    return name;
  }
  public String getGroup () {
    return group;
  }
  public Double getAvg () {
    return avg;
  }
  @Override
  public String toString () {
    return name + ":" + avg;
  }
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions