Android-java - 객체 내의 특정 값을 기준으로 객체 목록을 정렬하는 방법
개체 내의 특정 값을 기준으로 개체의 배열 목록을 정렬하려고 합니다.그런 일을 하기 위한 최선의 접근법은 무엇일까요?Collections.sort()를 비교기와 함께 사용해야 합니까?
변수 중 하나에 포함된 부동값을 기준으로 개체 목록을 정렬하려고 합니다.
편집: 지금까지의 내용은 다음과 같습니다.
public class CustomComparator implements Comparator<Marker> {
@Override
public int compare(Mark o1, Mark o2) {
return o1.getDistance().compareTo(o2.getDistance());
}
}
오류 상태: primitive type double에서 compareTo(double)를 호출할 수 없습니다.
대조군이 특정 유형 이외에는 반품할 수 없기 때문입니까?
Array List를 정렬하려면 다음 코드를 따릅니다.
Collections.sort(myList, new Comparator<EmployeeClass>(){
public int compare(EmployeeClass obj1, EmployeeClass obj2) {
// ## Ascending order
return obj1.firstName.compareToIgnoreCase(obj2.firstName); // To compare string values
// return Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId)); // To compare integer values
// ## Descending order
// return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values
// return Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId)); // To compare integer values
}
});
기본 정렬이 필요한 경우 Comparator 대신 Comparatible을 사용해야 합니다.
여기를 참조해 주십시오.이것이 도움이 될 수 있습니다.클래스는 언제 Comparatible 및/또는 Comparator여야 합니까?
시험해 보세요-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestSort {
public static void main(String args[]){
ToSort toSort1 = new ToSort(new Float(3), "3");
ToSort toSort2 = new ToSort(new Float(6), "6");
ToSort toSort3 = new ToSort(new Float(9), "9");
ToSort toSort4 = new ToSort(new Float(1), "1");
ToSort toSort5 = new ToSort(new Float(5), "5");
ToSort toSort6 = new ToSort(new Float(0), "0");
ToSort toSort7 = new ToSort(new Float(3), "3");
ToSort toSort8 = new ToSort(new Float(-3), "-3");
List<ToSort> sortList = new ArrayList<ToSort>();
sortList.add(toSort1);
sortList.add(toSort2);
sortList.add(toSort3);
sortList.add(toSort4);
sortList.add(toSort5);
sortList.add(toSort6);
sortList.add(toSort7);
sortList.add(toSort8);
Collections.sort(sortList);
for(ToSort toSort : sortList){
System.out.println(toSort.toString());
}
}
}
public class ToSort implements Comparable<ToSort> {
private Float val;
private String id;
public ToSort(Float val, String id){
this.val = val;
this.id = id;
}
@Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
@Override
public String toString(){
return this.id;
}
}
이게 너에게 더 도움이 될 것 같아.
Person p = new Person("Bruce", "Willis");
Person p1 = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas", "Cage");
Person p3 = new Person("John", "Travolta");
ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
}
});
이제 박스를 할 필요가 없습니다(즉, 작성할 필요가 없습니다).OBJECT
compareTo of Collections와 함께 설치된 새 연산자 사용 값 Of를 사용합니다.정렬..)
1) 오름차순의 경우
Collections.sort(temp, new Comparator<XYZBean>()
{
@Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
}
});
1) 디아스텐딩 오더용
Collections.sort(temp, new Comparator<XYZBean>()
{
@Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
}
});
코틀린에게는 아주 쉬워요!
listToBeSorted.sortBy { it.distance }
이를 사용하여 두 String을 비교할 수 있습니다.
Collections.sort(contactsList, new Comparator<ContactsData>() {
@Override
public int compare(ContactsData lhs, ContactsData rhs) {
char l = Character.toUpperCase(lhs.name.charAt(0));
if (l < 'A' || l > 'Z')
l += 'Z';
char r = Character.toUpperCase(rhs.name.charAt(0));
if (r < 'A' || r > 'Z')
r += 'Z';
String s1 = l + lhs.name.substring(1);
String s2 = r + rhs.name.substring(1);
return s1.compareTo(s2);
}
});
이제 Contact Data 클래스를 만듭니다.
public class ContactsData {
public String name;
public String id;
public String email;
public String avatar;
public String connection_type;
public String thumb;
public String small;
public String first_name;
public String last_name;
public String no_of_user;
public int grpIndex;
public ContactsData(String name, String id, String email, String avatar, String connection_type)
{
this.name = name;
this.id = id;
this.email = email;
this.avatar = avatar;
this.connection_type = connection_type;
}
}
contacts List는 다음과 같습니다.
public static ArrayList<ContactsData> contactsList = new ArrayList<ContactsData>();
Kotlin의 경우 이 기능을 사용할 수 있습니다.
fun sortList(list: List<YourCustomPOJOClass?>) {
//descending
Collections.sort(
list
) { o1, o2 -> Integer.valueOf(o1!!.intValueXYZ!!).compareTo(o2!!.intValueXYZ!!) }
// //ascending
// Collections.sort(
// list
// ) { o1, o2 -> Integer.valueOf(o2!!.intValueXYZ!!).compareTo(o1!!.intValueXYZ!!) }
}
그냥 전화하면 돼activity
또는fragment
타고
sortList(list)
"Android-java"는 "normal java"와 전혀 다르지 않습니다.그래서 네Collections.sort()
좋은 방법이 될 것 같아요.
public class DateComparator implements Comparator<Marker> {
@Override
public int compare(Mark lhs, Mark rhs) {
Double distance = Double.valueOf(lhs.getDistance());
Double distance1 = Double.valueOf(rhs.getDistance());
if (distance.compareTo(distance1) < 0) {
return -1;
} else if (distance.compareTo(distance1) > 0) {
return 1;
} else {
return 0;
}
}
}
ArrayList(Marker) arraylist;
사용방법:
Collections.sort(arraylist, new DateComparator());
개인 모델 클래스
class Person {
int id;
String name;
String fatherName;
public Person(int id, String name, String fatherName) {
this.id = id;
this.name = name;
this.fatherName = fatherName;
}
}
정렬
class SORT_BY_ID implements Comparator<Person> {
public int compare(Person a, Person b)
{
return a.id - b.id;
}
}
사용.
ArrayList<Person> personArrayList = new ArrayList<Person>();
personArrayList.add(new Person(111, "bb", "oakla"));
personArrayList.add(new Person(131, "aa", "fast"));
personArrayList.add(new Person(121, "cccc", "paokla"));
System.out.println("Before Sorted Array list of PErson");
for (int i=0; i<personArrayList.size(); i++)
System.out.println(personArrayList.get(i));
Collections.sort(personArrayList, new SORT_BY_ID());
System.out.println("After Sorted ");
for (int i=0; i<personArrayList.size(); i++)
System.out.println(personArrayList.get(i));
오브젝트를 비교할 수 있는를 만들거나 오브젝트가 모두 같은 클래스의 인스턴스일 경우 해당 클래스를 구현하도록 할 수 있습니다.그런 다음 Collections.sort()를 사용하여 실제 정렬을 수행할 수 있습니다.
모델 클래스:
public class ToDoModel implements Comparable<ToDoModel> {
private String id;
private Date taskDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getTaskDate() {
return taskDate;
}
public void setTaskDate(Date taskDate) {
this.taskDate = taskDate;
}
@Override
public int compareTo(ToDoModel another) {
return getTaskDate().compareTo(another.getTaskDate());
}
}
이제 Array List에서 데이터 설정
for (int i = 0; i < your_array_length; i++) {
ToDoModel tm = new ToDoModel();
tm.setId(your_id);
tm.setTaskDate(your_date);
mArrayList.add(tm);
}
배열 목록 정렬
Collections.sort(toDoList);
요약:.데이터가 날짜별로 정렬됩니다.
이 코드를 사용하고 있습니다.
Collections.sort(groupMemberList, new Comparator<GroupMember>() {
@Override
public int compare(GroupMember o1, GroupMember o2) {
return Long.valueOf(o2.getStatus()).compareTo(Long.valueOf(o1.getStatus()));
}
@Override
public boolean equals(Object obj) {
return false;
}
});
이 커스텀 컴퍼레이터 클래스를 사용하여 클라이언트 이름을 정렬하고 있는 모든 클라이언트에 관한 정보를 표시하는 리스트 뷰가 있습니다.이 set Strength(Collator)로 관리하고 있는 영어편지 외에 레렛이 조금 더 있습니다.세컨더리)
public class CustomNameComparator implements Comparator<ClientInfo> {
@Override
public int compare(ClientInfo o1, ClientInfo o2) {
Locale locale=Locale.getDefault();
Collator collator = Collator.getInstance(locale);
collator.setStrength(Collator.SECONDARY);
return collator.compare(o1.title, o2.title);
}
}
PRIMARY strength: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character.
SECONDARY strength: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings.
TERTIARY strength: Upper and lower case differences in characters are distinguished at tertiary strength (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary strength (such as "A" and "Ⓐ"). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings.
IDENTICAL strength: When all other strengths are equal, the IDENTICAL strength is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared, just in case there is no difference. For example, Hebrew cantellation marks are only distinguished at this strength. This strength should be used sparingly, as only code point value differences between two strings are an extremely rare occurrence. Using this strength substantially decreases the performance for both comparison and collation key generation APIs. This strength also increases the size of the collation key.
**Here is a another way to make a rule base sorting if u need it just sharing**
/* String rules="< å,Å< ä,Ä< a,A< b,B< c,C< d,D< é< e,E< f,F< g,G< h,H< ï< i,I"+"< j,J< k,K< l,L< m,M< n,N< ö,Ö< o,O< p,P< q,Q< r,R"+"< s,S< t,T< ü< u,U< v,V< w,W< x,X< y,Y< z,Z";
RuleBasedCollator rbc = null;
try {
rbc = new RuleBasedCollator(rules);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String myTitles[]={o1.title,o2.title};
Collections.sort(Arrays.asList(myTitles), rbc);*/
언급URL : https://stackoverflow.com/questions/9109890/android-java-how-to-sort-a-list-of-objects-by-a-certain-value-within-the-object
'programing' 카테고리의 다른 글
Quarkus 테스트에서 MariaDB devservices를 사용하는 방법 (0) | 2022.09.11 |
---|---|
노드 하나가 사망한 후 3노드 Galera 클러스터의 정의된 동작은 무엇입니까? (0) | 2022.09.11 |
Ajax POST 요청에 대한 Laravel csrf 토큰 불일치 (0) | 2022.09.11 |
base-2 이진수 문자열을 int로 변환합니다. (0) | 2022.09.11 |
MySQL에 삽입할 때 PHP에서 단일 따옴표 이스케이프 (0) | 2022.09.11 |