2016-09-19 3 views
1

M1, M2, M3, M4, M5, W1, W2, W3, W4, C1, C2와 같이 Person 클래스의 개체가 있습니다. 남자, W : 여성, C : 아이우선 순위에 따라 배열 재정렬

그들은 아래에 배열에 저장됩니다 : M은 어디

Person[] arr = {M1,M3,C1,W1,W3,M2,M4,W2,C2,W4,M5}; 

이제 배열은 객체의 각 유형에 대해 설정된 우선 순위에 따라 재 배열해야한다. Priorites는 열거과 같다 :

또한
enum Priority{ 
    One, 
    Two, 
    Three; 
} 

하는 순서는 예를 들면 동일하게 유지되었는지 확인 : M1은 M2 등등 M3 전에 와서한다 M2 앞에 와야 ...

입력 : 남자를위한Person[] arr = {M1,M3,C1,W1,W3,M2,M4,W2,C2,W4,M5}; 및 우선 순위 : 여자를위한 Priority.Two 우선 순위 : 자녀에 대한 Priority.One 우선 순위 : Priority.Three

예상 출력 :Person[] arr = {W1,W2,W3,W4,M1,M2,M3,M4,M5,C1,C2};

잘못된 출력 : 위해도 동일하게 유지해야하기 때문에Person[] arr = {W1,W3,W2,W4,M1,M5,M4,M3,M2,C2,C1};

후자는 잘못된 것입니다.

답변

1

에 대한 자신의 비교를 만들기에 대해 어떻게 이동하는 방법에 대한 링크입니다.

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

public class Person { 

private int priority; 
private String objName; 

Person(String name,int value){ 
    this.objName = name; 
    this.priority = value; 
} 

public int getPriority() { 
    return priority; 
} 

public void setPriority(int priority) { 
    this.priority = priority; 
} 

public String getObjName() { 
    return objName; 
} 

public void setObjName(String objName) { 
    this.objName = objName; 
} 

public static void main(String[] args) { 
    Person M1 = new Person("M1",Priority.valueOf("ONE").getValue()); 
    Person M2 = new Person("M2",Priority.valueOf("ONE").getValue()); 
    Person M3 = new Person("M3",Priority.valueOf("ONE").getValue()); 
    Person M4 = new Person("M4",Priority.valueOf("ONE").getValue()); 
    Person M5 = new Person("M5",Priority.valueOf("ONE").getValue()); 
    Person W1 = new Person("W1",Priority.valueOf("THREE").getValue()); 
    Person W2 = new Person("W2",Priority.valueOf("THREE").getValue()); 
    Person W3 = new Person("W3",Priority.valueOf("THREE").getValue()); 
    Person W4 = new Person("W4",Priority.valueOf("THREE").getValue());  
    Person C1 = new Person("C1",Priority.valueOf("TWO").getValue()); 
    Person C2 = new Person("C2",Priority.valueOf("TWO").getValue()); 

    Person[] arr = {M1,M3,C1,W1,W3,M2,M4,W2,C2,W4,M5}; 

    List<Person> list = Arrays.asList(arr); 

    System.out.println("Before sort..."); 
    for(Person p : list){ 
     System.out.println(p.getObjName()); 
    } 

    Collections.sort(list, new PersonComparator<Person>()); 

    System.out.println("After sort..."); 
    for(Person p : list){ 
     System.out.println(p.getObjName()); 
    } 
} 

} 

enum Priority{ 
ONE(1),TWO(2),THREE(3); 

private int value; 
public int getValue() { 
    return value; 
} 
Priority(int v){ 
    this.value = v; 
} 
} 

class PersonComparator<T> implements Comparator<Person> { 
public int compare(Person p1, Person p2) { 
    //Sorting based on priority 
    int v1 = p1.getPriority(); 
    int v2 = p2.getPriority(); 
    ; 
    if (v1 - v2 == 0) { 
     //Sorting based on object name 
     int i1 = Integer.parseInt(p1.getObjName().substring(1, 2)); 
     int i2 = Integer.parseInt(p2.getObjName().substring(1, 2)); 
     return i1 - i2; 
    } 
    return v1 - v2; 
} 
} 
+0

나는 이렇게 할 수 없다. 객체는 배열로 주어지며 Person 클래스를 수정할 수 없습니다. 각 객체 유형에 대한 우선 순위가 포함 된 Priority 열거 형 클래스 만 있습니다. 대체 방법을 제안 해 줄 수 있습니까? – RoyalTiger

+0

솔루션을 업데이트했습니다. – Vel

+0

감사합니다. @Vel .. 작동합니다. 나는 내 대답을 찾았 어 .. 고맙습니다. – RoyalTiger

1

필자는 Person 클래스에 대한 비교기를 만들어야 만 Person 객체가 Collections.sort() 메소드를 사용하여 컬렉션에서 정렬 될 수 있다고 생각합니다. 여기

다음은 사용자 정의 객체를 정렬 비교기 인터페이스를 사용하여 솔루션 클래스 http://www.tutorialspoint.com/java/java_using_comparator.htm

+0

나는 사람 클래스를 변경할 수 있다고 생각 생각하지 않는다 ... – RoyalTiger

+0

나는 문을 고쳐했다. 그것은 '재배치'되어야합니다. '정렬'되지 않았습니다. 나는이 단어가 오해의 소지가 있다고 생각한다. – RoyalTiger

2

봅니다 아래

final List<Person> persons = new ArrayList<>(); 
    IntStream.rangeClosed(1, 5).mapToObj(i -> new Person("M" + i, Priority.TWO)).forEach(persons::add); 
    IntStream.rangeClosed(1, 4).mapToObj(i -> new Person("W" + i, Priority.ONE)).forEach(persons::add); 
    IntStream.rangeClosed(1, 2).mapToObj(i -> new Person("C" + i, Priority.THREE)).forEach(persons::add); 
    persons.add(new Person("M11", Priority.TWO)); // test to sort by number 
    List<Person> sorted = persons.stream() 
      .sorted(Comparator.comparing(Person::getPriority).thenComparingInt(p -> Integer.parseInt(p.getName().substring(1)))) 
      .collect(Collectors.toList()); 
    System.out.println("Before sort " + persons.stream().map(Person::getName).collect(Collectors.toList())); 
    System.out.println("After sort " + sorted.stream().map(Person::getName).collect(Collectors.toList())); 

Before sort [M1, M2, M3, M4, M5, W1, W2, W3, W4, C1, C2, M11] 
After sort [W1, W2, W3, W4, M1, M2, M3, M4, M5, M11, C1, C2] 

OUPUT주의 사항 : 코드는 열거 클래스의 값의 순서에 따라 위의 열거의 값이 정렬됩니다

편집 - 1

Compartor

Comparator<Person> comp = new Comparator<Person>() { 
     @Override 
     public int compare(Person p1, Person p2) { 
      int co = p1.getPriority().compareTo(p2.getPriority()); 
      if (co == 0) 
       return Integer.parseInt(p1.getName().substring(1)) - Integer.parseInt(p2.getName().substring(1)); 
      return co; 
     } 
    }; 
+0

Saravana, Stream을 사용하지 않고도 동일한 작업을 수행 할 수 있습니까?내말은 내 솔루션이 될 것이라고 말해야한다. – RoyalTiger

+0

@RoyalTiger'Collections.sort' 또는 \t'Arrays.sort'에서 사용할 수있는 'Comparator'를 추가했다. – Saravana

관련 문제