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.

【Scala】TreeSetに格納した値をindex指定で取り出す

Posted at

概要

TreeSetは【Java】TreeSetの特徴を分かりやすく解説します。の記事で紹介されている通り、要素の重複を排除し、要素が自動で整列されるコレクションオブジェクトです。値を追加の度にソートしてくれるので、ソート処理を書かなくてよく便利なのですが、TreeSetからは直接index指定で値を取り出すことができないようです。
今回はこのTreeSetを元に、index指定でどうやって値を取り出すか記事を書いてみます。

対応方法

Java Program to Get the TreeSet Element By Indexの記事にある通り、色々やりようはあるのですが、個人的には「Method 2: Using .toArray() Method」にある配列に変換する方法が、シンプルかなと感じました。一度配列に格納した上で、index指定で値を取り出します。

実装サンプル

Javaでは上記の記事にあるような実装でいけますが、ここではScalaで配列に変換する実装サンプルを紹介します。実装のやり方はJavaとほぼ同じですね。

import scala.collection.immutable.TreeSet

object TreeSetToArray extends App {
  // 降順に設定する
  val ordering = Ordering[Int].reverse
  val sampleTreeSet = TreeSet(3, 4, 1, 2)(ordering)
  // 4, 3, 2, 1の順になる
  println(sampleTreeSet)

  // 配列に変換
  val sampleArray = sampleTreeSet.toArray
  // index1を指定した場合は「3」が返る
  println(sampleArray(1))

}

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?