2018年5月31日 星期四

[Java] 使用另一個列表進行排序

class Foo {
    private String id;
    public Foo(String id) { this.id = id; }
    public String getId() { return id; }
    @Override
    public String toString() { return id; }
}

List<Foo> list = Arrays.asList(new Foo("1"), new Foo("2"), new Foo("3"), new Foo("4"));
List<String> keys = Arrays.asList("2","1","3","4");

// before Java 8
List<Foo> result1 = new ArrayList<>(list);
Collections.sort(result1, new Comparator() {
    @Override
    public int compare(Foo o1, Foo o2) {
        return keys.indexOf(o1.getId()) < keys.indexOf(o2.getId()) ? -1 : 1;
    }
});

// after Java 8
List<Foo> result2 = list.stream()
    .sorted(Comparator.comparing(e -> keys.indexOf(e.getId())))
    .collect(Collectors.toList());

System.out.println(result1); // [2, 1, 3, 4]
System.out.println(result2); // [2, 1, 3, 4]

沒有留言:

張貼留言

[Java] Invalid HTTP method: PATCH

最近系統需要使用 Netty4,所以把衝突的 Netty3 拆掉,然後就出現了例外。 pom.xml <dependency> <groupId>com.ning</groupId> <artifactId>as...