1
class abc {
    String name;
    int id;
    int salary;
}

List list<abc>=new ArrayList();

Object of abc should be store based on sorted salary in List like max salary will be stored first then 2nd max will be stored then 3rd and soo on.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Gaurav Singh
  • 343
  • 1
  • 3
  • 11

3 Answers3

1

it's

List<abc> list=new ArrayList<>();

use

list.sort(Comparator<abc>).

or make abc implements Comparable and define the compareTo method. then use

list.sort()
Tokazio
  • 516
  • 2
  • 18
0

If you mean to sort the list you can use Collections.sort api.

If you mean to store it in dp sorted ( as you used java-ee tag) it will be stored in dp sorted unless its being cascaded by another object.

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43
  • No i want to store object based on sorted salary..if i use clln.sort(list); then it will not store based on sorted salary.. – Gaurav Singh Sep 30 '16 at 19:33
  • you can use custom comparator and sort based on your salary , anyway its really not a good practice to take the trouble to store the values in the db sorted , as you may need to add to this list later on , then u will need to remove all the entries , sort then and insert them again , if you need your records sorted you can use "ordered by" in your query – Amer Qarabsa Sep 30 '16 at 19:39
0

There are 2 ways to do sorting on a custom data type :

1) Comparator
2) Comparable

Using Comparable

class abc implements Comparable<abc> {
    String name;
    int id;
    int salary;

    public int compareTo(abc t1){
     return t1.salary - this.salary;
    }
}

Now use Collections.sort() on the arraylist, which would sort it for you.

Rishi
  • 1,163
  • 7
  • 12
  • Thxxx ...but i dont knw why they marks this question as duplicate...this was different..i was not asking cllns.sort(list) :) .....and thxx. – Gaurav Singh Sep 30 '16 at 19:51