2
1

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 1 year has passed since last update.

【Java, Kotlin, stream】オブジェクトリストをプロパティ名で日本語ソートする

Last updated at Posted at 2019-10-18

オブジェクトのリストをプロパティ名で日本語ソートしたい!

  • 折角なので(?)stream api で

実施環境

開発PC: Windows 10
Java: 8
Kotlin: 1.6

Java版

List modelList にモデルリストが格納済み

  • Model.name に日本語名が入っている
	Collator collator = Collator.getInstance( Locale.JAPANESE );
	collator.setStrength(Collator.IDENTICAL);
	collator.setDecomposition(Collator.FULL_DECOMPOSITION);
	List<Model> kanaSortedModelList = modelList.stream()
		.sorted(Comparator.comparing(Model::getName, Comparator.nullsLast(collator)))
		.collect(Collectors.toList());

Comparator.naturalOrder() だとunicode順になってちょっと不自然だったので・・・。

Kotlin 版

		// 日本語ソート
		val collator = Collator.getInstance(Locale.JAPANESE)
		collator.strength = Collator.IDENTICAL
		collator.decomposition = Collator.FULL_DECOMPOSITION
		val kanaSortedModelList: List<Model> =
            modelList.sortedWith(compareBy( nullsLast(collator) ){ it.name })

Kotlin の方が書き方はシンプルで分かりやすいですね。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?