2018. 3. 27. 21:01
반응형
Java를 다루다보면 많이 쓰는게 List(ArrayList), HashMap<String, Object> 인 것 같다.
HashMap<String, Object>는 JSON과도 밀접하게 관련이 있을 수 있다.
List 안에 HashMap을 넣은 다음 그걸 정렬해야할 때가 있다.
각 경우별로 몇가지 간단하게 정렬하는 예제를 통해 방법을 파악해봤다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
public class ListTest {
public static void main(String[] args) {
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
list.add(getStudent("peter", 21, 68.3));
list.add(getStudent("tom", 24, 78.3));
list.add(getStudent("taylor", 23, 64.3));
list.add(getStudent("hani", 31, 88.3));
list.add(getStudent("mike", 21, 68.3));
for(int i=0; i<list.size(); i++) System.out.println(list.get(i));
// 이름(String) 오름차순
Collections.sort(list, new Comparator<HashMap<String, Object>>() {
@Override
public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
String name1 = (String) o1.get("name");
String name2 = (String) o2.get("name");
return name1.compareTo(name2);
}
});
System.out.println();
for(int i=0; i<list.size(); i++) System.out.println(list.get(i));
// 나이(Integer) 내림차순
Collections.sort(list, new Comparator<HashMap<String, Object>>() {
@Override
public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
Integer age1 = (Integer) o1.get("age");
Integer age2 = (Integer) o2.get("age");
return age2.compareTo(age1);
}
});
System.out.println();
for(int i=0; i<list.size(); i++) System.out.println(list.get(i));
// 점수(Double) 오름차순
Collections.sort(list, new Comparator<HashMap<String, Object>>() {
@Override
public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
Double score1 = (Double) o1.get("score");
Double score2 = (Double) o2.get("score");
return score1.compareTo(score2);
}
});
System.out.println();
for(int i=0; i<list.size(); i++) System.out.println(list.get(i));
}
static HashMap<String, Object> getStudent(String name, int age, double score){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("age", age);
map.put("score", score);
return map;
}
}반응형
'dev' 카테고리의 다른 글
| [Java] BigDecimal을 이용하여 반올림, 내림(버림), 올림 (1) | 2018.04.16 |
|---|---|
| [git] 윈도우 github, bitbucket 사용자 변경 (0) | 2018.04.11 |
| [Java/Spring] 스프링 파일 업로드, 출력 (0) | 2018.04.03 |
| [MySQL] 없으면 insert, 있으면 update 하기 (0) | 2018.03.31 |
| [Java] csv 파일 읽기 (0) | 2018.03.18 |
| 윈도우에 apache2, php 설치, 톰캣과 연동 (0) | 2018.03.11 |
| [Java] 자바에서 윈도우 cmd 명령어 실행하기 (0) | 2018.03.04 |
| taskkill로 프로세스 한번에 다 죽이기 (0) | 2018.03.04 |