常見問題:如何使用自定義類的不同比較器對PriorityQueue中的對象進行排序?在Java中使用PriorityQueue與任何比較器
我試過用在適當的對與預期類似的排序結果在接下來的代碼中的對象的priorityqueues和列表的這個比較要做到:
class User{
private Integer id;
private String name;
public User(Integer i, String n){
this.id=i;
this.name=n;
}
public Integer getId() {return id;}
public String getName() {return name;}
@Override
public boolean equals(Object obj) {
if (this == obj)return true;
if (obj == null)return false;
if (getClass() != obj.getClass())return false;
User other = (User) obj;
if(id == null){
if (other.id != null)return false;
}else if(!id.equals(other.id))return false;
return true;
}
@Override
public String toString() {return "[id:" + id + ", name:" + name + "]";}
}
public class MyPriorityQueue {
public static Comparator<User> cmpId = Comparator.comparingInt(x -> x.getId());
public static Comparator<User> cmpNameLength = Comparator.comparingInt(x -> x.getName().length());
public static void main(String[] args) {
List<User> users = new ArrayList<User>(10);
users.add(new User(1,"11111"));
users.add(new User(3,"333"));
users.add(new User(5,"5"));
users.add(new User(4,"44"));
users.add(new User(2,"2222"));
Queue<User> ids = new PriorityQueue<User>(10, cmpId); //use first comparator
users.forEach(x-> ids.offer(x));
Queue<User> names = new PriorityQueue<User>(10, cmpNameLength); //use second comparator
names.addAll(users);
System.out.println("Variant_1.1:");
ids.forEach(System.out::println);
System.out.println("Variant_2.1:");
names.forEach(System.out::println);
System.out.println("Variant_1.2:");
users.sort(cmpId); //use first comparator
users.forEach(System.out::println);
System.out.println("Variant_2.2:");
users.sort(cmpNameLength); //use second comparator
users.forEach(System.out::println);
}
}
輸出:
Variant_1.1: //Failed sorted queue by user.id with using comporator cmpId
[id:1, name:11111]
[id:2, name:2222]
[id:5, name:5]
[id:4, name:44]
[id:3, name:333]
Variant_2.1: //Failed sorted queue by length of the user.name with cmpNameLength
[id:5, name:5]
[id:4, name:44]
[id:3, name:333]
[id:1, name:11111]
[id:2, name:2222]
Variant_1.2: // OK: correctly sorted list by user.id with cmpId comporator
[id:1, name:11111]
[id:2, name:2222]
[id:3, name:333]
[id:4, name:44]
[id:5, name:5]
Variant_2.2: //OK: for list by length of the user.name with cmpNameLength
[id:5, name:5]
[id:4, name:44]
[id:3, name:333]
[id:2, name:2222]
[id:1, name:11111]
我的預期即:
- 變體1.1和2.1的結果;
- 變體1.2和2.2的結果;
將是相同的,但它們是不同的。
我的問題:我爲排序priorytyqueue /比較器做了什麼錯誤,以及如何獲得排序結果的優先隊列作爲我的例子中的適當列表?
感謝您澄清有關「的forEach」。糾正代碼後「while(!ids.isEmpty())System.out.println(ids.poll());」而不是「ids.forEach(System.out :: println);」,獲得了預期的結果。 –