I am trying to sort the elements present in my arraylist in decreasing order. However, there seems to be some issue in the implementation. I am just a beginner in java, and am trying to use the most easiest method possible to sort.
student temp = new student(user_name,given_name,family_name,tot_marks);
for(int j=0;j<list1.size()-1;j++)
{
for(int k=0;k<list1.size();k++)
{
student sort1 = list1.get(j);
student sort2 = list1.get(k);
if(sort1.tot_marks < sort2.tot_marks)
{
temp.user_name=sort1.user_name;
temp.family_name=sort1.family_name;
temp.given_name=sort1.given_name;
temp.tot_marks=sort1.tot_marks;
sort2.user_name=temp.user_name;
sort2.family_name=temp.family_name;
sort2.given_name=temp.given_name;
sort2.tot_marks=temp.tot_marks;
sort1.family_name=sort2.family_name;
sort1.given_name=sort2.given_name;
sort1.tot_marks=sort2.tot_marks;
list1.add(sort1); //Adding sorted elements to the arraylist.
}
//If marks are same, sort on the basis of username.
else if(sort1.tot_marks == sort2.tot_marks)
{
//Compare usernames whichever is greater.
{
temp.user_name=sort1.user_name;
temp.family_name=sort1.family_name;
temp.given_name=sort1.given_name;
temp.tot_marks=sort1.tot_marks;
sort2.user_name=temp.user_name;
sort2.family_name=temp.family_name;
sort2.given_name=temp.given_name;
sort2.tot_marks=temp.tot_marks;
sort1.family_name=sort2.family_name;
sort1.given_name=sort2.given_name;
sort1.given_name=sort2.given_name;
sort1.tot_marks=sort2.tot_marks;
list1.add(sort1);
}
}
}
}
//Print the sorted list.
for (int i=0;i<list1.size();i++)
{
student display = list1.get(i);
System.out.println(display.tot_marks+","+display.given_name+"
"+display.family_name);
}
You could just do:
Collections.sort(list1, new Comparator<student>() {
#Override
public int compare(student one, student another) {
if (one.tot_marks == another.tot_marks) {
return 0;
}
return one.tot_marks > another.tot_marks ? 1 : -1;
}
});
However a few advices:
Class names like student are not very easy for the eye for java developers. Try using capitalized camel case class names (in this case Student)
Underscores in member names are also not very nice in java, try camel case names (totMarks). Even better is a geter, and setter for it, rather than leaving it public. (getTotMarks(), setTotMarks(int))
Also before doing something like you did, try researching a bit! There is a good chance, somebody else wrote it before you!
In java to sort a List you should use Collections.sort and a Comparator.
Collections.sort(list1, new Comparator<student>() {
public int compare(student a, student b) {
if(a.tot_marks < b.tot_marks)
return -1;
else if (a.tot_marks > b.tot_marks)
return 1;
else
return a.username.compareTo(b.username);
}
});
No need for that. You are adding duplicated to your list.
list1.add(sort1); //Adding sorted elements to the arraylist.
Check your swap logic. It should be:
TEMP = SORT1
SORT1 = SORT2
SORT2 = TEMP
The way to go is to ditch your approach and make your student class implement the Comparable interface: public class student implements Comparable<student>. Also, in Java, class names should start with upper case letters.
Once that you make your class implement this interface, you will be forced to implement the compareTo(student student) method.
In this method, you will implement your comparison logic:
public int compareTo(student student)
{
if(this.marks != student.marks)
{
return Integer.compare(this.marks, student.marks);
}
else
{
return this.name.compareTo(student.name);
}
}
Then, to sort your array, simply call like so:
List<student> students = ...
Collections.sort(students);
The above will call your implementation of the .compareTo and sort the array accordingly.
To Sort the arrayList in descending order please implement the Comparator interface
and as Denis rightly pointed out.Do not duplicate the elements
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MyArrayListSort {
public static void main(String a[]){
List<Student> list = new ArrayList<Student>();
list.add(new Student("Ram",3000));
list.add(new Student("John",6000));
list.add(new Student("Crish",2000));
list.add(new Student("Tom",2400));
Collections.sort(list,new MyMarkComp());
System.out.println("Sorted list entries: ");
for(Student e:list){
System.out.println(e);
}
}
}
class MyMarkComp implements Comparator{
#Override
public int compare(Student e1, Student e2) {
if(e1.getMarks() < e2.getMarks()){
return 1;
} else {
return -1;
}
}
}
class Student{
private String name;
private int mark;
public Student(String n, int s){
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMarks() {
return mark;
}
public void setMarks(int mark) {
this.mark = mark;
}
public String toString(){
return "Name: "+this.name+"-- Marks: "+this.mark;
}
}
Related
Say I have arraylist A and to compare 2 objects of A I do a.getDistanceFromPlayer() < b.getDistanceFromPlayer().
I want to now have list B which will have all of A's objects, but sorted where the first object is closest to player, and last object is furthest.
What might be the fastest way to do this?
Thanks
Have A implement Comparable and then define the method compareTo(Object other) like so:
public int compareTo(Object other) {
if( this.getDistanceFromPlayer() < other.getDistanceFromPlayer() ) {
return -1;
} else if( this.getDistanceFromPlayer() > other.getDistanceFromPlayer()) {
return 1;
}
return 0;
}
Now you can call Collections.sort() on your list of objects
Use Collections.sort with a custom comparator.
eg.
public class DistanceComparator implements Comparator<Integer>{
#Override
public int compare(YourObject o1, YourObject o2) {
if (o1.getDistanceFromPlayer() > o2.getDistanceFromPlayer())
{
return 1;
}
else if (o1.getDistanceFromPlayer() < o2.getDistanceFromPlayer())
{
return -1;
}
return 0;
}
}
Then in your program, call
Collections.sort(YourArrayInstance, new DistanceComparator())
You should make your class implement Comparable.
Then you can use Collections.sort() to sort your List.
If you want a sorted List AND an unsorted List, you'll have to make a copy.
Another option is to create a Comparator.
If you read the documentation for Collections, you'll see it has two sort methods.
One bases the sort on the objects' compareTo method (ie their "natural order").
The other bases the sort on a Comparator that is passed as the second argument.
Here's a link to another question that provides an example implementation of Comparable:
Example implementation of Comparable
Use a Custom Comparator :
B = Collections.sort(A, new CustomComparator());
public class CustomComparator implements Comparator<ClassA> {
#Override
public int compare(final ClassA a, final ClassA b) {
//Make sure you check that neither a nor b are null..
//..
if (a.getDistanceFromPlayer() < b.getDistanceFromPlayer()) {
return 1;
} else if (a.getDistanceFromPlayer() > b.getDistanceFromPlayer()) {
return -1;
}
return 0;
}
}
You can use a custom Comparator and sort your ArrayList, like this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Main {
public static class Player {
private final float distance;
public Player (final float position) {
this.distance = position;
}
public float getDistanceFrom () {
return distance;
}
#Override
public String toString() {
return "Player [distance=" + distance + "]";
}
}
public static void main(String[] args) throws Exception {
final ArrayList<Player> players = new ArrayList<Player> ();
players.add (new Player (2));
players.add (new Player (5));
players.add (new Player (-3));
players.add (new Player (1));
Collections.sort(players, new Comparator<Player> () {
#Override
public int compare(Player o1, Player o2) {
final float distance1 = o1.getDistanceFrom();
final float distance2 = o2.getDistanceFrom();
return (int) Math.signum (distance1 - distance2);
}
});
System.out.println(players);
}
}
And a fiddle for it.
I have class ABC
class ABC{
private List<XYZ> xyzList -- Though its list it contains single object;
private String txt;
}
class XYZ{
private long price;
}
I want to sort List abcList based on class XYZ price variable.
Please provide best possible approach for sorting in ascending order.
Have you tried one of these methods:
java.util.Collections.sort(List<T>)
Or
java.util.Collections.sort(List<T>, Comparator<? super T>)
One way is implement Comparable interface in XYZ and override compareTo and then Collections.sort(yourListOfXYZ) will sort the list.
Other way is using Comparator.
Collections.sort(xyzList, new Comparator<XYZ>() {
#Override
public int compare( XYZ e1,XYZ e2) {
return Long.valueOf(e1.getPrice()).compareTo(Long.valueOf(e2.getPrice()));
}
});
Try this
Collections.sort(xyzList);
I would suggest you look into the documentation for the Comparable interface. Possible even with the use of an PriorityQueue.
In you case you either need to make XYZ implement Comparable, provide a Comparator<XYZ> or a simpler option is to unwrap it and just use a List<Double> or a SortedSet<Double> to hold you prices.
Sample code from http://java2novice.com/java-collections-and-util/arraylist/sort-comparator/
public class MyArrayListSort {
public static void main(String a[]){
List<Empl> list = new ArrayList<Empl>();
list.add(new Empl("Ram",3000));
list.add(new Empl("John",6000));
list.add(new Empl("Crish",2000));
list.add(new Empl("Tom",2400));
Collections.sort(list,new MySalaryComp());
System.out.println("Sorted list entries: ");
for(Empl e:list){
System.out.println(e);
}
}
}
class MySalaryComp implements Comparator<Empl>{
#Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
class Empl{
private String name;
private int salary;
public Empl(String n, int s){
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+"-- Salary: "+this.salary;
}
}
I've got a public List<FriendProfile> friends = new ArrayList<FriendProfile>();. I initialize the friends list by reading the information from the server. The FriendProfile object contains a int called private int userPosition;
Once the friends list has been initialized, I would like to sort the friends list by having the FriendProfile object with the highest userPosition at index 0 of the list and then sort by accordingly, index 1 with the second highest userPosition ...
I guess I could write an sorting algorithm, yet I'm looking for prewritten code (maybe the JDK has some methods to offer?)
Help is appreciated!
Use Collections.sort() and specify a Comparator:
Collections.sort(friends,
new Comparator<FriendProfile>()
{
public int compare(FriendProfile o1,
FriendProfile o2)
{
if (o1.getUserPosition() ==
o2.getUserPosition())
{
return 0;
}
else if (o1.getUserPosition() <
o2.getUserPosition())
{
return -1;
}
return 1;
}
});
or have FriendProfile implement Comparable<FriendProfile>.
Implement Comparable Interface.
class FriendProfile implements Comparable<FriendProfile> {
private int userPosition;
#Override
public int compareTo(FriendProfile o) {
if(this.userPosition > o.userPosition){
return 1;
}
return 0;
}
}
Just Call the Collection.sort(List) method.
FriendProfile f1=new FriendProfile();
f1.userPosition=1;
FriendProfile f2=new FriendProfile();
f2.userPosition=2;
List<FriendProfile> list=new ArrayList<FriendProfile>();
list.add(f2);
list.add(f1);
Collections.sort(list);
The List will be sorted.
Now no need to Boxing (i.e no need to Creating OBJECT using new Operator use valueOf insted with compareTo of Collections.Sort..)
1)For Ascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
#Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
}
});
1)For Deascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
#Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
}
});
Use Collections.Sort and write a custom Comparator that compares based on userPosition.
use Comparator with Collections.sort method
java.util.Collections.sort(list, new Comparator<FriendProfile >(){
public int compare(FriendProfile a, FriendProfile b){
if(a.getUserPosition() > b.getUserPosition()){
return 1;
}else if(a.getUserPosition() > b.getUserPosition()){
return -1;
}
return 0;
}
});
see this link
There are two ways to do this.
1.
FriendProfile could implement the interface Comparable.
public class FriendProfile implements Comparable<FriendProfile>
{
public int compareTo(FriendProfile that)
{
// Descending order
return that.userPosition - this.userPosition;
}
}
...
Collections.sort(friendProfiles);
2.
You could write a Comparator.
public class FriendProfileComparator implements Comparator<FriendProfile>
{
public int compare(FriendProfile fp1, FriendProfile fp2)
{
// Descending order
return fp2.userPosition - fp1.userPosition;
}
}
...
Collections.sort(friendProfiles, new FriendProfileComparator());
When comparing objects rather than primitives note that you can delegate on to the wrapper objects compareTo. e.g. return fp2.userPosition.compareTo(fp1.userPosition)
The first one is useful if the object has a natural order that you want to implement. Such as Integer implements for numeric order, String implements for alphabetical. The second is useful if you want different orders under different circumstances.
If you write a Comparator then you need to consider where to put it. Since it has no state you could write it as a Singleton, or a static method of FriendProfile.
You can use java.lang.Comparable interface if you want to sort in only One way.
But if you want to sort in more than one way, use java.util.Compartor interface.
eg:
The class whose objects are to be Sorted on its roll_nos
public class Timet {
String name;
int roll_no;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getN() {
return roll_no;
}
public void setN(int n) {
this.roll_no = n;
}
public Timet(String name, int n) {
this.name = name;
this.roll_no = n;
}
public String toString(){
return this.getName();
}
}
The class for sorting:
public class SortClass {
public void go(){
ArrayList<Timet> arr = new ArrayList<Timet>();
arr.add(new Timet("vivek",5));
arr.add(new Timet("alexander",2));
arr.add(new Timet("catherine",15));
System.out.println("Before Sorting :"+arr);
Collections.sort(arr,new SortImp());
System.out.println("After Sorting :"+arr);
}
class SortImp implements Comparator<Timet>{
#Override
public int compare(Timet t1, Timet t2) {
return new Integer(t1.getN()).compareTo (new Integer((t2.getN())));
}
}
public static void main(String[] args){
SortClass s = new SortClass();
s.go();
}
}
Good day!
I have an object student with the following attributes:
class Student
String name
Date birthday
I used arrayList to store the Student Objects
My problem is, how can I sort the StudentList by birthday using the collecitons sort?.
List <Student> studentList = new ArrayList<Student>();
How can I code it?
Collections.sort(????);
Thank you
You can pass a Comparator to Collections.sort() to handle the sorting by birthday:
Collections.sort(studentList, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getBirthday().compareTo(s2.getBirthday());
}
});
You'll need to add getBirthday() to your Student class if you don't have it already.
In Java 8 you can sort the list with a one-liner using Lambda expressions and Comparator.comparing:
Collections.sort(studentList, Comparator.comparing(s -> s.getBirthday()));
Alternatively you can use the method reference:
Collections.sort(studentList, Comparator.comparing(Student::getBirthday));
Hi this is a sample that can help you to understand
package de.vogella.algorithms.sort.standardjava;
import java.util.Comparator;
public class MyIntComparable implements Comparator<Integer>{
#Override
public int compare(Integer o1, Integer o2) {
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
}
package de.vogella.algorithms.sort.standardjava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Simple2 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(4);
list.add(3);
list.add(7);
list.add(2);
list.add(1);
Collections.sort(list, new MyIntComparable());
for (Integer integer : list) {
System.out.println(integer);
}
}
}
You need to write a custom comparator.
Something like:
Collections.sort(studentList, new Comparator<Student>() {
public int compare(Strudent a, Strudent b) {
return a.birthday.compareTo(b.birthday);
}
});
Here is tutorial from java to learn more about it.
http://download.oracle.com/javase/tutorial/collections/interfaces/order.html
This can be a tricky interview question :)
The best and reusable way i've found to solve a similar problem was to implement the interface Comparator and also creating custom Comparator according to my needs, which can be reused.
I leave here an example how to sort an ArrayList of Person according to their name attribute and also according to their gender attribute (which don't have any lexicography natural order).
The trick was defining a enum class with the custom attribute from which i wanted to sort. Applying a custom comparator to that enum attribute, the compareTo() method apply the order according to the natural order in which the values are declared (in this example male, female, others).
import java.util.*;
public class Person {
public enum Gender {
male,female, others
}
String name;
int age;
Gender gender;
public Person(String name, int age, Gender gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public Gender getGender() {
return gender;
}
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
public static void printPersons(List<Person> personList) {
for (int i = 0; i < personList.size(); i++) {
System.out.println(personList.get(i).toString());
}
}
public static void printSortedByAgePersons(List<Person> personList) {
Collections.sort(personList, Person.COMPARE_BY_NAME);
for (int i = 0; i < personList.size(); i++) {
System.out.println(personList.get(i).toString());
}
}
public static void printSortedByGender(List<Person> personList) {
Collections.sort(personList, Person.COMPARE_BY_GENDER);
printPersons(personList);
}
public static Comparator<Person> COMPARE_BY_NAME = new Comparator<Person>() {
#Override
public int compare(Person o1, Person o2) {
return o1.getName().compareTo(o2.getName());
}
};
public static Comparator<Person> COMPARE_BY_GENDER = new Comparator<Person>() {
#Override
public int compare(Person o1, Person o2) {
return o1.getGender().compareTo(o2.getGender());
}
};
// lets test this :
public static void main(String args[]) {
Person p1 = new Person("André", 22, Gender.male);
Person p2 = new Person("Minder", 19, Gender.others);
Person p4 = new Person("Maria", 19, Gender.female);
Person p3 = new Person("Pedro", 25, Gender.male);
List<Person> personList = new ArrayList<Person>();
personList.add(p1);
personList.add(p2);
personList.add(p3);
personList.add(p4);
System.out.println("original list:");
printPersons(personList);
System.out.println("------------------------------------------");
System.out.println("sorted list by name in alphabetical order");
printSortedByAgePersons(personList);
System.out.println("------------------------------------------");
System.out.println("sorted list by custom order(gender)");
printSortedByGender(personList);
}
}
I have to sort an array here is the code I have. When I try to utilize Arrays.sort() I get tons of errors. Anyone know what I am doing wrong? This is really my first time sorting and using arrays with constructors.
import java.util.Scanner;
import java.util.Arrays;
public class CoffeeDriver {
//main method
public static void main (String[] args){
Item[] itemObject = new Item[] {
new Item("Donut", .75),
new Item("Coffee", 1.00),
new Item("Bagel", 1.25),
new Item("Milk", 1.50),
new Item("Water", 2.00)};
Scanner input = new Scanner(System.in);
String decision;
System.out.println ("Welcome to Wings Coffee Shop");
System.out.println ("We have a great list of tasty items on our menu.");
System.out.println ("Would you like to see these items sorted by");
System.out.println ("name or by price? (n/p): ");
decision = input.nextLine();
sortName(itemObject);
sortPrice(itemObject);
}
//method to sort by item name and display
public static void sortName (Item[] itemObject){
Arrays.sort(itemObject);
System.out.println(itemObject);
}
//method to sort by item price and display
public static void sortPrice (Item[] array){
Arrays.sort(array);
for (int i = 0; i < array.length; i++){
System.out.println (array[i]);
}
}
}
public class Item
{
private String itemName = ""; //setting up the name
private double itemPrice=0.0; //Setting price variable
public Item(String name, double price) //Constructor
{
itemName = name;
itemPrice = price;
}
public String getitemName() //retuns name
{
return itemName;
}
public double getitemPrice() //returns price
{
return itemPrice;
}
public void setitemName(String name) //sets name
{
itemName = name;
}
public void setitemPrice (double price) //sets price
{
itemPrice = price;
}
}
Your Item class doesn't implement compareable. The sort method states: "Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array)."
But since you want to sort by two different things, implementing comparable won't get you very far, it's better to use a Comparator (http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html).
So your sort by name would look something like this (just replace the method part of compare(Item o1, Item o2) with the criteria you'd like the array to be sorted).
// method to sort by item name and display
public static void sortName(Item[] itemObject) {
Arrays.sort(itemObject, new Comparator<Item>() {
#Override
public int compare(Item o1, Item o2) {
return o1.getitemName().compareTo(o2.getitemName());
}
});
printArr(itemObject);
}
and your sortPrice like that:
// method to sort by item price and display
public static void sortPrice(Item[] array) {
Arrays.sort(array, new Comparator<Item>() {
#Override
public int compare(Item o1, Item o2) {
return Double.compare(o1.getitemPrice(), o2.getitemPrice());
}
});
printArr(array);
}
Also to print your results in a nice legible way it's generally a good idea to overwrite the toString() method in your class so that you can just write System.out.println(item); (toString is called automatically in that case).
Okay to get the content nicely printed we first add a toString() Method to your item class:
#Override
public String toString() {
return itemName + ": " + itemPrice;
}
That will just return the item's name and it's price when called. To print the array's content now nicely we'll just iterate through all it's members:
private static void printArr(Item[] arr) {
for(Item i : arr) {
System.out.println(i); // the same as System.out.println(i.toString()); - Java calls the toString method automatically in this case we you give it an object
}
}
Now we can just call this function everywhere you want to print the contents of an item array, like after sorting them!
Arrays.sort takes a Comparator which is used to perform the sort.
A Comparator used to find the difference between 2 items.
public static void sortName (Item[] itemObject){
Arrays.sort(itemObject, new Comparator<Item>() {
public int compare(Item a, Item b) {
if(a.getitemName() == null){
return b.getitemName() == null ? 0 : -1;
}
return a.getitemName().compareTo(b.getitemName());
}
});
}
public static void sortPrice (Item[] array){
Arrays.sort(array, new Comparator<Item>() {
public int compare(Item a, Item b) {
return Double.compare(a.getitemPrice(), b.getitemPrice());
}
});
}
You need to implement the compareTo method in your Item class, and declare it to implement the Comparable interface.
See How to use Comparable for an example.