Sort ArrayList Java


Description:

This example gives you how to sort an ArrayList using Comparator. The ArrayList contains user defined objects. By using Collections.sort[] method you can sort the ArrayList. You have to pass Comparator object which contains your sort logic. The example sorts the Empl objects based on highest salary.


Code:
package com.java2novice.arraylist; 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 list = new ArrayList[]; 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{ @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; } }

Output:
Sorted list entries: Name: John-- Salary: 6000 Name: Ram-- Salary: 3000 Name: Tom-- Salary: 2400 Name: Crish-- Salary: 2000

List Of All ArrayList Sample Programs:

Everything in java is an object, except primitives. Primitives are int, short, long, boolean, etc. Since they are not objects, they cannot return as objects, and collection of objects. To support this, java provides wrapper classes to move primitives to objects. Some of the wrapper classes are Integer, Long, Boolean, etc.

You can never get enough of what you dont really need.


Video liên quan

Chủ Đề