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?

素朴、そして簡潔

Last updated at Posted at 2025-12-13

埋め草記事です

こういうtweetを見かけました。

簡潔に書ける人はまあ大勢いらっしゃるでしょうけど、「簡潔な」コード例を二つほどでっち上げたので貼っておきます。

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class SecondMax {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            List<Integer> list = new ArrayList<>();
            while ( list.size() < 5 ) {
                list.add(scanner.nextInt());
            }
            list.sort(Comparator.reverseOrder());
            if ( list.get(0) == list.get(1) ) {
                System.out.println("No second maximum, but at least two same numbers are maximums.");
            } else {
                System.out.println("Second maximum is " + list.get(1));
            }
        }
    }
}
import java.util.stream.IntStream;
import java.util.Scanner;
import java.util.Comparator;

public class SecondMax2 {
    public static void main(String[] args) {
        try ( Scanner scanner = new Scanner(System.in) ) {
            Object[] result;
            result = IntStream.range(0,5)
                               .map(i -> scanner.nextInt())
                               .boxed()
                               .sorted(Comparator.reverseOrder())
                               .toArray();
            if ( ((Integer)result[0]).equals((Integer)result[1]) ) {
                System.out.println("Two same maximum numbers, no second max.");
            } else {
                System.out.println("Second max is " + (Integer)result[1]);
            }
        }
    }
}

Tweetでちらっと書いたけど、入力が5個でintの範囲と分かっているのでこれで済みます。入力がもっと複雑だったり、長さがもっと長かったりしたらこれでは駄目、です。そうすると最初に出てきた素朴に毎回比較して入れ替える、をやらないといけないかも知れませんね。

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?