[英]How to keep adding values to a key that already exists, when the values are in an ArrayList? Input is coming in from a scanner to create a TreeMap
我正在尝试从用户那里接收输入,其中每行必须由一些文本(键),后跟制表符, double
精度字面量(值)和换行符组成。
如果允许用户继续输入相同的键,然后输入/t
,然后输入一个不同的值和/n
,那么我该如何编写一个程序,将树中的值不断添加到相同的键中?
每个键都有一个ArrayList
,这是我卡住的地方,因为我不知道如何为不同的行/键继续添加到数组列表中。
这是我到目前为止的内容:
TreeMap<String, ArrayList<Double>> categoryMap = new TreeMap<>();
Double val = 0.0;
String inputKey = "";
System.out.println("Welcome, please enter text");
Scanner scn = new Scanner(System.in);
dataSource = scn;
try
{
// adds all words of input to a string array
while (dataSource.hasNextLine())
{
ArrayList<Double> valueMap = new ArrayList<>();
inputKey = dataSource.next();
val = dataSource.nextDouble();
valueMap.add(val);
if (categoryMap.get(inputKey) == null)
{
categoryMap.put(inputKey, valueMap);
}
else
{
categoryMap.put(inputKey, valueMap);
}
dataSource.nextLine();
}
}
// Exception if no lines detected and shows message
catch (IllegalArgumentException lineExcpt)
{
System.out.println("No lines have been input: " + lineExcpt.getMessage());
}
finally
{
scn.close();
}
return categoryMap;
我是Java的新手,只有大约一个月的经验。
您应该从地图上获取该键的arraylist并在其中添加值,例如else内的categoryMap.get (inputKey).add(val)
的东西,代码可能会有所改善,但是我现在使用的是phome ...
这是while
循环内的逻辑while
需要进行一些修改。 当前,您每次都用一个新值覆盖值列表。
这是您的纸上物品:
double
创建一个新列表,并将其用作值。 double
到它。 在代码中,我们只需要修改您所做的:
String inputKey = dataSource.next();
double val = dataSource.nextDouble();
List<Double> list = categoryMap.get(inputKey);
if (list == null) // If the key does not exist
{
list = new ArrayList<>(); // create a new list
list.add(val); // with the given double
categoryMap.put(inputKey, list); // and use it as the value
}
else // Else
{
list.add(val) // (got the list already) add the double to it
}
如果您使用Java 8,则映射具有computeIfAbsent
方法。
List<Double> addTo = map.computeIfAbsent(key, ArrayList::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.