質問は正規表現を使用しますが、仮定については、これはされていないクラス割り当てなどのソリューションを必要としません。正規表現。また、キーごとに複数の値を処理し、短いソリューション:
Map<String, List<String>> map = Files.lines(Paths.get("data.txt")).map(s -> s.replace("(", "").replace(")", ""))
.collect(groupingBy(s -> (s.split(","))[0], mapping(s -> (s.split(",", -1))[1].trim(), toList())));
System.out.println(map);
は、結果として得られたマップを印刷します:
{xyz=[AB], pqrst=[1E], abcd=[01]}
説明:
Files.lines(...) //reads all lines from file as a java 8 stream
map(s-> s.replace) // removes all parenthesis from each line
collect(groupingBy(s -> (s.split(","))[0] //collect all elements from the stream and group them by they first part before the ","
mapping(mapping(s -> (s.split(",", -1))[1].trim(), toList()) //and the part after the "," should be trimmed, -1 makes it able to handle empty strings, collect those into a list as the value of the previously grouping
代替はに置き換える代わりに、2つの単純なの、交換してください削除する(と)使用することができます
s.replaceAll("\\(|\\)", "")
最も読みやすいものが不明です。
投稿した内容を投稿してください。 –
http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java、http://stackoverflow.com/questions/2088037/trim-characters-in-java canを参照してください。ここで助けてください。 –
Javaのどのバージョンを使用しますか?流れはファイルから読んで、マップの権利を保存していますか? –