How to sort String or Object in List vs ArrayList


 

Phần 1 : Sort String

Chúng ta tạo ra 1 class SortPerson_String.java như sau:

package thaihoanghai.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortPerson_String {
	// we initialize list person with type String
	List<String> personList = new ArrayList<String>();

	public SortPerson_String() {
		// at here we create 4 person with names kobee - jenny - ducky - justina
		personList.add("Kobee");
		personList.add("Jenny");
		personList.add("Ducky");
		personList.add("Justina");
	}
	/**
	 * method is used to add new person with name
	 * @param name
	 */
	void addPerson(String name){
		personList.add(name);
	}

	// sort my list by name's person
	public void sortList(){
		System.out.println("Before===================================");
		System.out.println(personList);
		System.out.println("After.===================================");
		Collections.sort(personList);
		System.out.println(personList);
	}

	public static void main(String[] args) {
		SortPerson_String myList = new SortPerson_String();
		myList.sortList();

	}
}

kết quả sau khi run :
d1

 

Phần 2 : Sort by Object Using implements Comparable

Bài tập này chúng ta sẻ sort theo đối tượng các bạn xem demo của mình sau đây : Vẩn là sắp xếp theo name

Note 1 :

This Class được implements interface Comparable

Tạo 1 class Person.java như sau


package thaihoanghai.sort;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Person implements Comparable<Person>{
	private String id;
	private String name;
	private String address;
	private int age;
	private Date birthDay;

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String id, String name, String address, int age, Date birthDay) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
		this.age = age;
		this.birthDay = birthDay;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Date getBirthDay() {
		return birthDay;
	}
	public void setBirthDay(Date birthDay) {
		this.birthDay = birthDay;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return this.name +" - "+getMyDate(this.birthDay);
	}

	public String getMyDate(Date mydate){
		String result = new SimpleDateFormat("dd/MM/yyyy").format(mydate);
		return result;
	}

	/**
	 * Note this method when we implement interface comparable , we must override method compareTo
	 * At here we sort by Name's person
	 */
	@Override
	public int compareTo(Person obj) {
		return this.name.compareTo(obj.name);
	}

}

Chúng ta ra 1 class SortPerson_Object.java

package thaihoanghai.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class SortPerson_Object {
	List<Person> personList = new ArrayList<Person>();

	@SuppressWarnings("deprecation")
	public SortPerson_Object(){
		personList.add(new Person("ID001", "Kobee", "D24/3/2", 20, new Date("10/10/1991")));
		personList.add(new Person("ID002", "Jenny", "B24/3/2", 21, new Date("10/10/1990")));
		personList.add(new Person("ID003", "Ducky", "A24/3/2", 19, new Date("10/10/1992")));
		personList.add(new Person("ID004", "Justina", "A24/3/2", 18, new Date("10/10/1993")));
	}

	public void sortPerson(){
		System.out.println("Before===================================");
		System.out.println(personList);
		System.out.println("After.===================================");
		Collections.sort(personList);
		System.out.println(personList);
	}

	public static void main(String[] args) {
		SortPerson_Object personList = new SortPerson_Object();
		personList.sortPerson();
	}
}

Kết quả sau khi run :

d1

Phần 3 : Sort Object using implement Comparator .

Note : Chúng ta sẻ tạo ra 1 class MyCompare implement Comparator

Probleam của chúng ta. Chúng ta muốn Sort nhiều hơn 1 điều kiện. Ở đây mình Sort theo BirthDate vs Name của Person

Chúng ta sử dụng lại class person.java ở phía trên luôn nha.

Chúng ta tạo class SortPerson_MultiObject.java

package thaihoanghai.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class SortPerson_MultiObject {
	List<Person> personList = new ArrayList<Person>();

	@SuppressWarnings("deprecation")
	public SortPerson_MultiObject(){
		personList.add(new Person("ID001", "Kobee", "D24/3/2", 20, new Date("10/10/1991")));
		personList.add(new Person("ID002", "Jenny", "B24/3/2", 21, new Date("10/10/1990")));
		personList.add(new Person("ID003", "Ducky", "A24/3/2", 19, new Date("10/10/1990")));
		personList.add(new Person("ID004", "Justina", "A24/3/2", 18, new Date("10/10/1993")));
	}

	public void sortPerson(){
		System.out.println("Before==========Not-Sort=========================");
		System.out.println(personList);
		System.out.println("\n\n");

		System.out.println("After - 1 ==============Sort Name=====================");
		Collections.sort(personList);
		System.out.println(personList);
		System.out.println("\n\n");

		System.out.println("After - 2 ==============Sort BirtDate and Name=====================");
		Collections.sort(personList,new PersonCompare());
		System.out.println(personList);
		System.out.println("\n\n");
	}

	public static void main(String[] args) {
		SortPerson_MultiObject personList = new SortPerson_MultiObject();
		personList.sortPerson();
	}

	class PersonCompare implements Comparator<Person>{
		@Override
		public int compare(Person p1, Person p2) {
			return p1.getMyDate(p1.getBirthDay()).compareTo(p2.getMyDate(p2.getBirthDay()));
		}

	}
}

Kết quả sau khi Run:
d1

Chúc các bạn thành công.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: