0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Java8のリストソート方法

Posted at

Java8のリストソート方法

java8のリストソートは簡単です。

ソート対象DTO

@Data
public class Dto {
    private String id;
    private String name;
    private int age;
}

リストソート

public class TestListSort {
    public static void main(String args[]) {
        // リスト定義
        List<Dto> list = new ArrayList<>();
        list.add(new Data("001", "DTO1", 10));
        list.add(new Data("001", "DTO1", 5));
        list.add(new Data("003", "DTO3", 4));
        list.add(new Data("002", "DTO2", 4));
        
        // ソート処理(id、ageの昇順)
        list.sort(Comparator.comparing(Dto::getId).thenComparing(Dto::getAge));
        // ソート結果検証
        list.forEach(dto -> {
            System.oup.println("id=" + dto.getId() + " name=" + dto.getName()) + " age=" + dto.getAge());
        });
    }    
       
}
 

リストソート後、新しいリスト生成する場合

List<Dto> sortedList = list.stream().sorted(Comparator.comparing(Dto::getId).thenComparing(Dto::getAge)).collect(Collectors.toList());

id昇順、age降順の場合

list.sort(Comparator.comparing(Dto::getId).thenComparing(Comparator.comparing(Dto::getId).reversed()));
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?