Answer the question
In order to leave comments, you need to log in
How to sort TreeSet in ascending and descending order?
Unable to sort the TreeSet by one of the class elements
Here's what the task looks like:
The file “a.csv” contains a list of students who took exams, indicating the name, group and grades. Information about each student is stored in a separate line. Read information into a linked list (LinkedList). Create two collections of type TreeSet. TreeSet elements
are objects containing the student's last name and GPA. In the first
collection, the lists are sorted in ascending order of the average score; in the
second, in descending order. Print new collections on the screen.
What I managed to write at the moment (I tried using Comparable):
import java.io.*;
import java.util.*;
class Capital {
stringname;
stringgroup;
ArrayList grade = new ArrayList<>();
double sr;
}
class Asd implements Comparable{
String fname;
double midd;
public Asd (String ffname,double mid){
fname = ffname;
mid = 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 list = new LinkedList<>();
TreeSet tree1 = new TreeSet<>();
TreeSet tree2 = new TreeSet<>();
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 < (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 < 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);
}
}
}
Sample 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 the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question