programing

개체 목록을 속성별로 정렬하는 방법

goodcopy 2022. 7. 31. 22:11
반응형

개체 목록을 속성별로 정렬하는 방법

나는 간단한 수업이 있다.

public class ActiveAlarm {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;
}

★★★★★★★★★★★★★★★★★」List<ActiveAlarm> con별로 . 오름차순으로 정렬하는 방법timeStarted으로 by, by, by, by.timeEnded구구도 와와? ???C++에서는 범용 알고리즘과 오버로드 연산자<를 사용하고 있습니다만, Java는 처음입니다.

중 하나를 만듭니다.ActiveAlarmComparable<ActiveAlarm> 「」를 실장합니다.Comparator<ActiveAlarm>후, 콜:그럼 전화 주세요.

Collections.sort(list);

또는

Collections.sort(list, comparator);

일반적으로 하나의 "자연" 정렬 순서가 있는 경우 구현하는 것이 좋습니다.그렇지 않은 경우(특정 순서로 정렬할 필요가 있지만 다른 순서로 정렬할 필요가 있는 경우)를 구현하는 것이 좋습니다.이 특정한 상황은 어느 쪽으로든 갈 수 있어요, 솔직히 말해서...난 좀 더 유연한 방법을 택할 것 같아

편집: 구현 예시:

public class AlarmByTimesComparer implements Comparator<ActiveAlarm> {
  @Override
  public int compare(ActiveAlarm x, ActiveAlarm y) {
    // TODO: Handle null x or y values
    int startComparison = compare(x.timeStarted, y.timeStarted);
    return startComparison != 0 ? startComparison
                                : compare(x.timeEnded, y.timeEnded);
  }

  // I don't know why this isn't in Long...
  private static int compare(long a, long b) {
    return a < b ? -1
         : a > b ? 1
         : 0;
  }
}

사용법

예:

class Score {

    private String name;
    private List<Integer> scores;
    // +accessor methods
}

    Collections.sort(scores, new Comparator<Score>() {

        public int compare(Score o1, Score o2) {
            // compare two instance of `Score` and return `int` as result.
            return o2.getScores().get(0).compareTo(o1.getScores().get(0));
        }
    });

Java 8 이상에서는 람다 식을 사용하여 비교기 인스턴스를 나타낼 수 있습니다.

Collections.sort(scores, (s1, s2) -> { /* compute and return int */ });

JAVA 8 이상의 답변(Lambda 식 사용)

Java 8에서는 이것을 더욱 쉽게 하기 위해 람다 표현이 도입되었습니다!Comparator() 오브젝트의 모든 발판을 포함하는 오브젝트를 작성하는 대신 다음과 같이 단순화할 수 있습니다(오브젝트를 예로 사용).

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.timeStarted-a2.timeStarted);

또는 더 짧음:

Collections.sort(list, Comparator.comparingInt(ActiveAlarm ::getterMethod));

이 하나의 문장은 다음과 같습니다.

Collections.sort(list, new Comparator<ActiveAlarm>() {
    @Override
    public int compare(ActiveAlarm a1, ActiveAlarm a2) {
        return a1.timeStarted - a2.timeStarted;
    }
});

Lambda 표현식은 코드의 관련 부분(메서드 서명 및 반환 대상)만 입력하면 된다고 생각합니다.

질문의 또 다른 부분은 여러 필드와 비교하는 것이었습니다. 하려면 표현식을 ..thenComparing()를 하나의비교로 함수:

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.timeStarted-a2.timeStarted             
       .thenComparing ((ActiveAlarm a1, ActiveAlarm a2) -> a1.timeEnded-a2.timeEnded)
);

는 먼저 을 위의 the the the the the the the the로 합니다.timeStarted, 그리고 다음으로timeEnded(「」)의)timeStarted를 참조해 주세요.

마지막 한 가지 주의사항:'롱' 또는 '인트' 원형을 비교하는 것은 쉬우며, 하나만 빼면 됩니다.오브젝트('Long' 또는 'String')를 비교할 경우 빌트인 비교를 사용하는 것이 좋습니다.예:

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.name.compareTo(a2.name) );

편집: Lukas Eder가 알려준 것 감사합니다..thenComparing()★★★★★★ 。

다음 두 가지 방법 중 하나로 목록을 정렬할 수 있습니다.

1. 비교기 사용 : 여러 곳에서 정렬 로직을 사용해야 할 경우 정렬 로직을 한 곳에서 사용하려면 다음과 같이 익명의 내부 클래스를 작성하거나 비교기를 추출하여 여러 곳에서 사용할 수 있습니다.

  Collections.sort(arrayList, new Comparator<ActiveAlarm>() {
        public int compare(ActiveAlarm o1, ActiveAlarm o2) {
            //Sorts by 'TimeStarted' property
            return o1.getTimeStarted()<o2.getTimeStarted()?-1:o1.getTimeStarted()>o2.getTimeStarted()?1:doSecodaryOrderSort(o1,o2);
        }

        //If 'TimeStarted' property is equal sorts by 'TimeEnded' property
        public int doSecodaryOrderSort(ActiveAlarm o1,ActiveAlarm o2) {
            return o1.getTimeEnded()<o2.getTimeEnded()?-1:o1.getTimeEnded()>o2.getTimeEnded()?1:0;
        }
    });

'long'이 아닌 'long'을 사용할 수 있었다면 속성에 대한 null check를 받을 수 있습니다.

2. 동등한 제품 사용 (자연 주문) :정렬 알고리즘이 항상 하나의 속성을 고수하는 경우: 'Comparable'을 구현하는 클래스를 작성하고 아래 정의된 대로 'compareTo' 메서드를 재정의합니다.

class ActiveAlarm implements Comparable<ActiveAlarm>{

public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;

public ActiveAlarm(long timeStarted,long timeEnded) {
    this.timeStarted=timeStarted;
    this.timeEnded=timeEnded;
}

public long getTimeStarted() {
    return timeStarted;
}

public long getTimeEnded() {
    return timeEnded;
}

public int compareTo(ActiveAlarm o) {
    return timeStarted<o.getTimeStarted()?-1:timeStarted>o.getTimeStarted()?1:doSecodaryOrderSort(o);
}

public int doSecodaryOrderSort(ActiveAlarm o) {
    return timeEnded<o.getTimeEnded()?-1:timeEnded>o.getTimeEnded()?1:0;
}

}

자연스러운 순서에 따라 정렬하는 호출 정렬 방식

Collections.sort(list);

java8+에서는 다음과 같이 한 줄로 쓸 수 있습니다.

collectionObjec.sort(comparator_lamda) ★★★★★★★★★★★★★★★★★」comparator.comparing(CollectionType::getterOfProperty)

코드:

ListOfActiveAlarmObj.sort((a,b->a.getTimeStarted().compareTo(b.getTimeStarted())))
 

또는

ListOfActiveAlarmObj.sort(Comparator.comparing(ActiveAlarm::getTimeStarted))
public class ActiveAlarm implements Comparable<ActiveAlarm> {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;

    public int compareTo(ActiveAlarm a) {
        if ( this.timeStarted > a.timeStarted )
            return 1;
        else if ( this.timeStarted < a.timeStarted )
            return -1;
        else {
             if ( this.timeEnded > a.timeEnded )
                 return 1;
             else
                 return -1;
        }
 }

그그 、 하충충충충을 。후에 전화하시면 .Collections.sort()리스트에 있습니다.

Java8에서는 와 를 조합하여 보다 깔끔하게 할 수 있습니다.

예:

class Student{

    private String name;
    private List<Score> scores;

    // +accessor methods
}

class Score {

    private int grade;
    // +accessor methods
}

    Collections.sort(student.getScores(), Comparator.comparing(Score::getGrade);

Guava 비교 체인:

Collections.sort(list, new Comparator<ActiveAlarm>(){
            @Override
            public int compare(ActiveAlarm a1, ActiveAlarm a2) {
                 return ComparisonChain.start()
                       .compare(a1.timestarted, a2.timestarted)
                       //...
                       .compare(a1.timeEnded, a1.timeEnded).result();
            }});

Stream API를 사용한 Java-8 솔루션:

A. 언제timeStarted ★★★★★★★★★★★★★★★★★」timeEndedpublic와 같이) (public 메서드 getter "getter":

List<ActiveAlarm> sorted = 
    list.stream()
        .sorted(Comparator.comparingLong((ActiveAlarm alarm) -> alarm.timeStarted)
                        .thenComparingLong((ActiveAlarm alarm) -> alarm.timeEnded))
        .collect(Collectors.toList());

B. 언제timeStarted ★★★★★★★★★★★★★★★★★」timeEnded 가지다public 메서드 getter "getter":

List<ActiveAlarm> sorted = 
    list.stream()
        .sorted(Comparator.comparingLong(ActiveAlarm::getTimeStarted)
                        .thenComparingLong(ActiveAlarm::getTimeEnded))
        .collect(Collectors.toList());

의 「」를 .list 자체 명령어:

A. 언제timeStarted ★★★★★★★★★★★★★★★★★」timeEndedpublic와 같이) (public 메서드 getter "getter":

list.sort(Comparator.comparingLong((ActiveAlarm alarm) -> alarm.timeStarted)
                    .thenComparingLong((ActiveAlarm alarm) -> alarm.timeEnded));

B. 언제timeStarted ★★★★★★★★★★★★★★★★★」timeEnded 가지다public 메서드 getter "getter":

list.sort(Comparator.comparingLong(ActiveAlarm::getTimeStarted)
                    .thenComparingLong(ActiveAlarm::getTimeEnded));

종업원 POJO 클래스

package in.ac.adit.oop.sort;

public class Employee {
    private int id;
    private String name;
    private String department;

    public int getId() {
        return id;
    }

    public Employee() {
        super();
    }

    public Employee(int id, String name, String department) {
        super();
        this.id = id;
        this.name = name;
        this.department = department;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", department=" + department + "]";
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }
}

종업원을 관리하는 종업원 클래스

package in.ac.adit.oop.sort;

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

    public class Example {
        public static void main(String[] args) {
    
            /*
             * Create 10 Employee Object
             */
            Employee emp1 = new Employee(1, "Nayan", "IT");
            Employee emp2 = new Employee(2, "Siddarth", "CP");
            Employee emp3 = new Employee(3, "Samarth", "AE");
            Employee emp4 = new Employee(4, "Bhavesh", "CV");
            Employee emp5 = new Employee(5, "Sam", "FT");
            Employee emp6 = new Employee(6, "Keyur", "IT");
            Employee emp7 = new Employee(7, "Bala", "ME");
            Employee emp8 = new Employee(8, "Mitul", "ME");
            Employee emp9 = new Employee(9, "Kamlesh", "EE");
            Employee emp10 = new Employee(10, "Piyush", "EE");
    
            /*
             * List of Employee Object
             */
            List<Employee> employeeList = new ArrayList<Employee>();
            employeeList.add(emp1);
            employeeList.add(emp2);
            employeeList.add(emp3);
            employeeList.add(emp4);
            employeeList.add(emp5);
            employeeList.add(emp6);
            employeeList.add(emp7);
            employeeList.add(emp8);
            employeeList.add(emp9);
            employeeList.add(emp10);
    
            CustomObjectSort customObjectSort = new CustomObjectSort();
            List<Employee> sortByDepartment = customObjectSort.sortByDepartment(employeeList);
    
            /*
             * Sorted By Department
             */
            for (Employee employee : sortByDepartment) {
                System.out.println(employee);
            }
    
            /*
             * Sorted By Name
             */
            List<Employee> sortByName = customObjectSort.sortByName(employeeList);
    
            for (Employee employee : sortByName) {
                System.out.println(employee);
            }
    
            /*
             * Sorted By Id
             */
            List<Employee> sortById = customObjectSort.sortById(employeeList);
    
            for (Employee employee : sortById) {
                System.out.println(employee);
            }
    
        }
    }

커스텀 정렬

package in.ac.adit.oop.sort;


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

public class CustomObjectSort {

    public List<Employee> sortByName(List<Employee> employeeList) {

        Collections.sort(employeeList, new Comparator<Employee>() {

            @Override
            public int compare(Employee employee1, Employee employee2) {
                return employee1.getName().compareTo(employee2.getName());
            }

        });
        return employeeList;
    }

    public List<Employee> sortByDepartment(List<Employee> employeeList) {

        Collections.sort(employeeList, new Comparator<Employee>() {

            @Override
            public int compare(Employee employee1, Employee employee2) {
                return employee1.getDepartment().compareTo(employee2.getDepartment());
            }

        });
        return employeeList;
    }

    public List<Employee> sortById(List<Employee> employeeList) {

        Collections.sort(employeeList, new Comparator<Employee>() {

            @Override
            public int compare(Employee employee1, Employee employee2) {
                return employee1.getId() - employee2.getId();
            }

        });
        return employeeList;
    }

}

자신의 것을 사용하고 패스할 수 있습니다.

에서는 static Java static을 해야 합니다.Collections.sort 。 다음은 된 후 입니다.다음은 처음에 순서대로 정렬된 후 끝에 정렬된 CompanyRole 개체 목록의 예입니다.을 사용하다

private static void order(List<TextComponent> roles) {

    Collections.sort(roles, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            int x1 = ((CompanyRole) o1).getBegin();
            int x2 = ((CompanyRole) o2).getBegin();

            if (x1 != x2) {
                return x1 - x2;
            } else {
                int y1 = ((CompanyRole) o1).getEnd();
                int y2 = ((CompanyRole) o2).getEnd();
                return y2 - y1;
            }
        }
    });
}

, 그럼 이렇게 .Comparator.comparing()개체의 속성을 기준으로 목록을 정렬하는 메서드입니다.

class SortTest{
    public static void main(String[] args) {
        ArrayList<ActiveAlarm> activeAlarms = new ArrayList<>(){{
            add(new ActiveAlarm("Alarm 1", 5, 10));
            add(new ActiveAlarm("Alarm 2", 2, 12));
            add(new ActiveAlarm("Alarm 3", 0, 8));
        }};

        /* I sort the arraylist here using the getter methods */
        activeAlarms.sort(Comparator.comparing(ActiveAlarm::getTimeStarted)
                .thenComparing(ActiveAlarm::getTimeEnded));

        System.out.println(activeAlarms);
    }
}

이 작업을 수행하기 전에 정렬의 기준이 되는 속성의 getter 메서드를 정의해야 합니다.

public class ActiveAlarm {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;

    public ActiveAlarm(String name, long timeStarted, long timeEnded) {
        this.name = name;
        this.timeStarted = timeStarted;
        this.timeEnded = timeEnded;
    }

    public long getTimeStarted() {
        return timeStarted;
    }

    public long getTimeEnded() {
        return timeEnded;
    }

    @Override
    public String toString() {
        return name;
    }
}

출력:

[Alarm 3, Alarm 2, Alarm 1]

Collections.sort()를 호출하여 오브젝트의 다른 속성을 비교하기 위해 써야 하는 Comparator를 전달할 수 있습니다.

전술한 바와 같이, 다음의 순서로 정렬할 수 있습니다.

  • 구현Comparable
  • 패스해 주세요.Comparator로로 합니다.Collections.sort

다 '다 하다'는Comparable되어 「」가 됩니다.Comparator이렇게 나름의 논리.Comparable각 사용 사례마다 고유한 구현이 있는 반면 가치 개체에 가장 적합한 정렬 방식입니다.

Java(Java 8 이상)에서 개체 목록을 정렬하는 가장 쉽고 최선의 방법입니다.fruitName 속성을 기준으로 과일 바구니를 정렬합니다.

과일 POJO:

class Fruit
{
    int price;
    String fruitName;
    
    
    public Fruit(int price, String fruitName) {
        super();
        this.price = price;
        this.fruitName = fruitName;
    }


    public int getPrice() {
        return price;
    }


    public void setPrice(int price) {
        this.price = price;
    }


    public String getFruitName() {
        return fruitName;
    }


    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }


    @Override
    public String toString() {
        return "Fruits [price=" + price + ", fruitName=" + fruitName + "]";
    }
    
}

이제 과일을 목록에 추가하고 정렬해 봅시다.

List<Fruit> basketOfFruits = new ArrayList<>();
        basketOfFruits.add(new Fruit(123, "oranges"));
        basketOfFruits.add(new Fruit(45, "nectarine"));
        basketOfFruits.add(new Fruit(369, "blueberries"));
        basketOfFruits.add(new Fruit(248, "apple"));
        basketOfFruits.add(new Fruit(968, "peaches"));
        basketOfFruits.add(new Fruit(436, "grapes"));
        basketOfFruits.add(new Fruit(596, "figs"));
        
       //sorting by the property fruitName
        Collections.sort(basketOfFruits, (f1, f2)->{return f1.getFruitName().compareTo(f2.getFruitName());}); 

이제 목록(예: basketOfFruits)을 인쇄할 수 있으며 목록 내의 과일은 오름차순(사전학적으로)으로 정렬됩니다.출력은 다음과 같습니다.

[Fruits [price=248, fruitName=apple], Fruits [price=369, fruitName=blueberries], Fruits [price=596, fruitName=figs], Fruits [price=436, fruitName=grapes], Fruits [price=45, fruitName=nectarine], Fruits [price=123, fruitName=oranges], Fruits [price=968, fruitName=peaches]]

Collections.sort() 대신 Java 스트림을 사용할 수도 있습니다(Java 8 이상).다음은 Java 스트림을 사용하는 코드입니다.

List<Fruit> sortedFruits = basketOfFruits.stream().sorted( (f1, f2)->{return f1.getFruitName().compareTo(f2.getFruitName());}).collect(Collectors.toList());

이 목록은 Collections.sort()와 같은 방법으로 정렬되지만 정렬된 항목은 다른 목록 "sorted Fruits"에 저장/수집됩니다.따라서 목록의 정렬된 항목을 인쇄하려면 이 경우 "basket Of Fruits"가 아닌 "sorted Fruits"를 인쇄해야 합니다.

언급URL : https://stackoverflow.com/questions/5805602/how-to-sort-list-of-objects-by-some-property

반응형