私がそれをどのように解釈したか、さらに重要なことに、実際の実装ではなく、入力と出力 (期待) にどのように焦点を当てているかによって、質問を言い換えてみます。
文字列を解析する必要があります
"Apple;Mango;Orange:1234;Orange:1244;...;"
':'
ある意味で、果物に関連付けられた値 ( の後の数字) を取得できます。
- この例では、 AppleとMangoの両方に値がないため、空のリストを受け取る必要があります。
- Orangeのリストを受け取る必要があり
1234, 1244
ます。
もちろん、あなたの直感はHashMap
その場ですぐにわかりますが、詳細にこだわりすぎなければ、誰かが常により良い解決策を提示してくれるかもしれません。
いくつかの白い斑点が残っています。
- 値のない果物には既定値を指定する必要がありますか?
- 値のない果物をマップに含める必要がありますか?
- 入力エラーはどのように処理する必要がありますか?
- 重複する値をどのように処理する必要がありますか?
このコンテキストがあれば、コードを書き始めることができます。
import java.util.*;
public class FruitMarker {
public static void main(String[] args) {
String input = "Apple;Mango;Orange:1234;Orange:1244";
// replace with parameter processing from 'args'
// avoid direct implementations in variable definitions
// also observe the naming referring to the function of the variable
Map<String, Collection<Integer>> fruitIds = new HashMap<String, Collection<Integer>>();
// iterate through items by splitting
for (String item : input.split(";")) {
String[] fruitAndId = item.split(":"); // this will return the same item in an array, if separator is not found
String fruitName = fruitAndId[0];
boolean hasValue = fruitAndId.length > 1;
Collection<Integer> values = fruitIds.get(fruitName);
// if we are accessing the key for the first time, we have to set its value
if (values == null) {
values = new ArrayList<Integer>(); // here I can use concrete implementation
fruitIds.put(fruitName, values); // be sure to put it back in the map
}
if (hasValue) {
int fruitValue = Integer.parseInt(fruitAndId[1]);
values.add(fruitValue);
}
}
// display the entries in table iteratively
for (Map.Entry<String, Collection<Integer>> entry : fruitIds.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
}
このコードを実行すると、次の出力が得られます。
Mango => []
Apple => []
Orange => [1234, 1244]