hi i have the next problem i have an array or arraylist from class Student which has firstname, lastname and grade.
How can i sort them by grade (value) - ascending and descending?

package zadacha_1;

import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class Zadacha_2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<Student> students = new ArrayList<Student>();
		
		students.add(new Student("Stefan", "Stefanov", 3));
		students.add(new Student("Petar", "Petrov", 4));
		students.add(new Student("Angel", "Angelov", 5));
		students.add(new Student("Boiko", "Borisov", 6));
		students.add(new Student("Georgi", "Parvanov", 3));
		students.add(new Student("Atanas", "Atanasov", 4));
		students.add(new Student("Naiden", "Naidenov", 5));
		students.add(new Student("Georgi", "Georgiev", 6));
		students.add(new Student("Pencho", "Penchev", 2));
		students.add(new Student("Ivan", "Ivanov", 2));
		
		
		Student[] arrayStudents = new Student[10];
		for (int i = 0; i <10; i++){
			arrayStudents[i] = students.get(i);
		}
	
		//Arrays.sort(arrayStudents);
		for (Student name : arrayStudents){
			System.out.println(name.getFirstName());
		}
	}

}

I need it sorted by value not by key

You can have a method in the Student class:

public int comporeByGrade(Student st) {
    return grade - st.getGrade();
}

The above method will return positive if this Student is greater than the argument, negative if it is lower than and zero if their grades are equal.

So write a for loop that loops through the array. Take each Student and use that method in order to determine which Student is greater than the other and then use any of the sorting algorithms provided.


If the issue here is not to implement a sorting algorithm for educational purposes but simply sort the list using any means necessary then you can have the Student class implement the Comparable interface.
Then implement its method: compareTo and use the sort method of the Arrays class.
Of course you will need to convert the ArrayList to an array for the sort method of the Arrays class, but that shouldn't be a problem

Hi I have written the following code and it runs fine.It takes user input and stores it in an ArrayList of student beans. It prints the students in descending order of grades.Hope it helps.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class SortStudentsByGrade 
{
   List<Students> arrlist = new ArrayList<Students>();
	
	public static void main(String[] args)
    {
	 SortStudentsByGrade s = new SortStudentsByGrade();
	 s.getStudentsByGrade();
    }

	private void getStudentsByGrade() 
	{
		try
		{
			System.out.println("Add a new student?");
			
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String ans = br.readLine();
			
			if(ans.equalsIgnoreCase("Y"))
			{
				
				//make a new student
				Students s = new Students();
				
				System.out.println("Enter first name : ");
				String firstName = br.readLine();
				System.out.println("Enter last name : ");
				String lastName = br.readLine();
				System.out.println("Enter grade : ");
				int grade = Integer.parseInt(br.readLine());
				
				s.setFirstName(firstName);
				s.setLastName(lastName);
				s.setGrade(grade);
				
				//add to the arraylist
				arrlist.add(s);
				
				getStudentsByGrade();
				
			}
			else
			{
				//sort the students by descending grade
				Collections.sort(arrlist,new StudentsSort());
				
				//print the list
				System.out.println("FirstName LastName Grade");
				for(Students st:arrlist)
				{
					System.out.print(st.getFirstName() + "    ");
					System.out.print(st.getLastName() + "     ");
					System.out.println(st.getGrade());
				}
			}
			
			
			
		}
	    catch(IOException e)
	    {
		  
	    }	
		
	}  
}
public class Students {
	String firstName;
	String lastName;
	int grade;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getGrade() {
		return grade;
	}

	public void setGrade(int grade) {
		this.grade = grade;
	}

}
import java.util.Comparator;

import com.sun.org.apache.bcel.internal.generic.RETURN;


public class StudentsSort implements Comparator<Students> 
{
    public int compare(Students s1,Students s2)
    {
    	if(s1.getGrade()==s2.getGrade())
    		return 0;
    	else if(s1.getGrade()>s2.getGrade())
    		return -1;
    	else
    		return 1;
    		
    }
}
commented: Provided unhelpful erronous ready solution -1

No, with your way, he will get an OutOfMemoryException:

private void getStudentsByGrade() {
  if (...) {
     getStudentsByGrade();
  } 
}

After pressing yes too many times.

Couldn't you just use this in a single method:

while (ans.equalsIgnoreCase("Y")) {

}

yes thanks .better to use while . otherwise the code is fine , i believe.

i got it working.

package zadacha_1;

import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class Zadacha_2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<Student> students = new ArrayList<Student>();
		
		students.add(new Student("Stefan", "Stefanov", 3));
		students.add(new Student("Petar", "Petrov", 4));
		students.add(new Student("Angel", "Angelov", 5));
		students.add(new Student("Boiko", "Borisov", 6));
		students.add(new Student("Georgi", "Parvanov", 3));
		students.add(new Student("Atanas", "Atanasov", 4));
		students.add(new Student("Naiden", "Naidenov", 5));
		students.add(new Student("Georgi", "Georgiev", 6));
		students.add(new Student("Pencho", "Penchev", 2));
		students.add(new Student("Ivan", "Ivanov", 2));
		
		
		Student[] arrayStudents = new Student[10];
		for (int i = 0; i <10; i++){
			arrayStudents[i] = students.get(i);
		}
		boolean doMore = true;
		while (doMore){
			doMore = false;
			for (int i = 0; i < arrayStudents.length-1; i++){
				
				
				int one = arrayStudents[i].getGrade();
				int two = arrayStudents[i+1].getGrade();
					if (one > two){
						Student temp = arrayStudents[i+1];
						arrayStudents[i+1] = arrayStudents[i];
						arrayStudents[i] = temp;
						doMore=true;
					}
			}	
			
		}
		 for (Student name : arrayStudents){
			 System.out.println(name.getFirstName()+" "+ name.getLastName()+" "+ name.getGrade());
		 }
		
	}

}

yes thanks .better to use while . otherwise the code is fine , i believe.

Actually you will get an Exception, because your method keeps calling itself. If the user continues to enter "Y" the program will run out of memory and crash.
Just because it will happen after many attempts of inserting "Y" it's not a excuse for writing unstable code

Actually you will get an Exception, because your method keeps calling itself. If the user continues to enter "Y" the program will run out of memory and crash.
Just because it will happen after many attempts of inserting "Y" it's not a excuse for writing unstable code

The method only callls itself when there is a new addition.So that reason for the exception does not hold.However typing in Y several will make an exception.So while is required,thats true.

So that reason for the exception does not hold.However typing in Y several will make an exception

That is what I said:

If the user continues to enter "Y" the program will run out of memory and crash.

hi i have the next problem i have an array or arraylist from class Student which has firstname, lastname and grade.

Hi you can use the standard Collections.sort(..) method, but this doesn't use the power of your multi-core mashine. Thus I use the sort-implementation from happy-collections library (Apache License 2.0). Here is an example, which solves your problem.

ArrayList<Student> studentsList = new ArrayList<Student>();

studentsList.addAll(Arrays.asList(
		new Student[]{
				new Student("Stefan", "Stefanov", 3),
				new Student("Petar", "Petrov", 4),
				new Student("Angel", "Angelov", 5),
				new Student("Boiko", "Borisov", 6),
				new Student("Georgi", "Parvanov", 3),
				new Student("Atanas", "Atanasov", 4),
				new Student("Naiden", "Naidenov", 5),
				new Student("Georgi", "Georgiev", 6),
				new Student("Pencho", "Penchev", 2),
				new Student("Ivan", "Ivanov", 2)
				}));

//sort student-list with fast parallel-sort, it combines many sorting algorithms and use the power of multi-core processor
Collections_1x0.sort(studentsList, new Comparator<Student>() {

	@Override
	public int compare(Student s1, Student s2) {
		return s1.getAccount() - s2.getAccount();
	}
});

/*
//classic way to sort by using standard JDK sort method
Collections.sort(studentsList, new Comparator<Student>() {

	@Override
	public int compare(Student s1, Student s2) {
		return s1.getAccount() - s2.getAccount();
	}
});
*/

for (Student s : studentsList){
	System.out.println(s);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.