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

JavaのStream APIを使ってコレクションの要素をランダムな順序に並べ替える

Last updated at Posted at 2024-11-24

JavaのStream APIを使ってコレクションの要素をランダムな順序に並べ替えるには、Collections.shuffleメソッドを使用するのが一般的です。以下にその方法を示します。

まず、Streamをリストに変換し、そのリストをシャッフルしてから再びStreamに変換します。

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

public class Main {
    public static void main(String[] args) {
        // サンプルデータ
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("xiaoming", 35),
            new Person("Diana", 28)
        );

        // リストをシャッフル
        Collections.shuffle(people);

        // シャッフルされたリストを再びStreamに変換
        Stream<Person> shuffledStream = people.stream();

        // 結果を表示
        shuffledStream.forEach(System.out::println);
    }
}

この方法では、以下の手順を踏んでいます:

1.元のStreamをリストに変換します。
2.Collections.shuffleメソッドを使ってリストをシャッフルします。
3.シャッフルされたリストを再びStreamに変換します。
これにより、元のStreamの要素がランダムな順序で処理されるようになります。

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