본문 바로가기

IT/Java

ArrayList 문자열, 객체 정렬

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
package com.lgcns.test;

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

public class Test {
	
	ArrayList<String> strList;
	ArrayList<People> objList;
	
	public Test(){
		
	}
	
	public void init(){
		strList = new ArrayList<String>();
		strList.add("erick");	strList.add("yulia");	strList.add("koyo");
		strList.add("anna");	strList.add("son");	strList.add("messi");	strList.add("ryu");	strList.add("kim");
		
		objList = new ArrayList<People>();
		objList.add(new People("giyeon","33"));
		objList.add(new People("minji","30"));
		objList.add(new People("youngjun","34"));
		objList.add(new People("chan","35"));
		objList.add(new People("hungmin","28"));
		
	}
	
	public void work(){
		init();
		sortStringList();
		sortObjectList();
	}
	
	public void sortStringList(){
		// 오름차순
		Collections.sort(strList);
		printList(strList);
		// 내림차순 - 오름차순 한 다음에 reverse를 해야 내림차순이 된다.
		Collections.reverse(strList);
		printList(strList);
	}
	
	public void sortObjectList(){
		// 오름차순
		Collections.sort(objList);
		printObjectList(objList);
		// 내림차순 - 오름차순 한 다음에 reverse를 해야 내림차순이 된다.
		Collections.reverse(objList);
		printObjectList(objList);
	}
	
	public void printList(List list){
		Iterator<String> iter = list.iterator();
		while(iter.hasNext()){
			System.out.print(iter.next()+"\t");
		}
		System.out.println();
	}
	
	public void printObjectList(List list){
		Iterator<People> iter = list.iterator();
		People temp;
		while(iter.hasNext()){
			temp = iter.next();
			System.out.print(temp.getName()+":"+temp.getAge()+"\t");
		}
		System.out.println();
	}
	
	public static void main(String[] args){
		new Test().work();
	}
}

class People implements Comparable<People>{
	
	String name, age;
	
	public People(String name, String age){
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}



	@Override
	public int compareTo(People people) {
		// TODO Auto-generated method stub
		if(this.age.compareTo(people.getAge()) < 0){
			return -1;
		}else if(this.age.compareTo(people.getAge()) > 0){
			return 1;
		}else{
			return 0;
		}
	}
	
}

'IT > Java' 카테고리의 다른 글

Java ArrayList Controller  (0) 2020.06.22
Java StringController  (0) 2020.06.22
Java Socket File 전송  (1) 2019.07.03
[API] FileUtils  (0) 2019.06.25
BubbleSort 및 ArrayList, String API 요약  (0) 2018.05.08