2017-09-13 日報

昨日投稿できなかったので2日分をまとめて投稿。

今日調べたこと

[Java] Map -> List 変換

Map<Object, T>#values() を取得して List<T> にしたかった。
ArrayList のコンストラクタにあるのね。一発でした。

List<T> list = new ArrayList<T>(map.values());

【Java実践】Map→List、List→Map変換方法まとめ | 侍エンジニア塾ブログ | プログラミング入門者向け学習情報サイト

[Java] Java で LeftPad / RightPad

Commons LangStringUtils にあるけど、わざわざ Commons Lang を導入するほどでもないので自作。

実際には RightPad しか必要なかったんだけど、どうせなので LeftPad も実装しておいた。

public class StringUtility {
    /**
     * 方向
     */
    public enum Direction {
        Left,
        Right
    }

    /**
     * 文字列が空か判定します
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null) {
            return true;
        }
        if ("".equals(str)) {
            return true;
        }
        return false;
    }

    /**
     * 対象文字列が指定された桁数になるまで左側に文字列を追加します
     *
     * @param source 対象文字列
     * @param length 桁数
     * @param chars 挿入する文字列
     * @return
     */
    public static String leftPad(String source, int length, String chars) {
        return fillString(source, Direction.Left, length, chars);
    }

    /**
     * 対象文字列が指定された桁数になるまで右側に文字列を追加します
     *
     * @param source 対象文字列
     * @param length 桁数
     * @param chars 挿入する文字列
     * @return
     */
    public static String rightPad(String source, int length, String chars) {
        return fillString(source, Direction.Right, length, chars);
    }

    /**
     * 対象文字列が指定された桁数になるまで左or右に文字列を追加します
     *
     * @param source 対象文字列
     * @param direction 左右
     * @param length 桁数
     * @param chars 挿入する文字列
     * @return
     */
    public static String fillString(String source, Direction direction, int length, String chars) {
        if (isEmpty(chars)) {
            throw new IllegalArgumentException("undefined argument: chars");
        }
        if (source == null) {
            source = "";
        }

        StringBuilder sb = new StringBuilder(source);

        // 指定された長さになるまで文字列を追加する
        while (length > sb.length()) {
            switch (direction) {
                case Left:
                    // 前方に追加
                    int len = sb.length() + chars.length();
                    if (len > length) {
                        // 長くなりすぎるので追加する文字列を詰める
                        String cs = chars.substring(0, chars.length() - (len - length));
                        sb.insert(0, cs); //前方に挿入
                    } else {
                        sb.insert(0, chars);
                    }
                    break;
                case Right:
                    // 後方に追加
                    sb.append(chars);
                    break;
            }
        }

        // 指定された長さになるよう切り詰めて返す
        return sb.toString().substring(0, length);
    }
}

コメント

このブログの人気の投稿

Classpath entry org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER is marked for publish/export but is not exported on the project classpath

蛍光灯フリッカー現象 (ちらつき) の対策

[node.js] CP932のテキストを読み込む