당신은에 소개 된 람다 식을 사용할 수 있습니다 Comparable/Comparator 인터페이스를 구현하지 않고 객체를 정렬하는 Java8
다음은 람다를 사용하여 개체를 정렬하고 표시하는 코드 스 니펫입니다.
class Student
{
int id;
String name;
public Student(int id, String name)
{
this.id = id;
this.name = name;
}
public String toString()
{
return id +" " +name;
}
}
public class SortDemo
{
public static void main(String[] args)
{
List<Student> list=new ArrayList<Student>();
//Adding Objects
list.add(new Student(1,"XYZ"));
list.add(new Student(3,"ABC"));
list.add(new Student(2,"PQR"));
System.out.println("Sorting on the basis of name...");
// implementing lambda expression
Collections.sort(list,(p1,p2)->{return p1.name.compareTo(p2.name);});
list.forEach((s)->System.out.println(s));
}
}
예, 사용 비교기 – ControlAltDel
제가 질문에서 언급 한 바와 같이, 객체가 구현 할 수없는 비교기 – BenParker93
왜 당신이 그 2 인터페이스를 사용하지 않고 정렬해야합니까? 그들은 당신이 정렬 할 수 있도록 설계되었습니다. – Ash