LoginSignup
0
1

More than 5 years have passed since last update.

Java8 の Stream で ltsv パース

Last updated at Posted at 2016-02-16

業務で ltsvっぽい形式の文字列のパースを行うことがあり、Java の Stream を利用して書いてみた時のメモ

package ltsv;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static Map<String, String> parse(String ltsv) {
        return Stream.of(ltsv.split("\t"))
                     .filter(s -> s.contains(":"))
                     .map(s -> s.split(":"))
                     .collect(Collectors.toMap(p -> p[0], p -> p[1]));
    }

    public static void main(String[] args) {
        String ltsvsample = "host: 127.0.0.1\tuser: m3y\tprotocol: HTTP/1.1";
        Main.parse(ltsvsample).forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
    }
}

//protocol: HTTP/1.1
//host: 127.0.0.1
//user: m3y

toMap で 0 と 1 指定するところもっとうまく書けないかな。。

※ 上記は業務で利用しているコードではありません^^;

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