我必须保存一个Collection并访问它(从一个循环中),但我无法找到一种方法...对我的程序有任何建议..我刚刚开始学习Java。感谢
public class Main {
public static void main(String[] args) {
// my hashmap
Map<String, List<String>> test_01 = new HashMap<>();
Scanner scanner = new Scanner(System.in);
String answer;
List<String> name = new ArrayList<>();
List<String> time = new ArrayList<>();
String lake_Name, lake_time;
do {
System.out.println("Enter the name of the lake : ");
lake_Name = scanner.nextLine();
name.add(lake_Name);
System.out.println("Enter the name of the running time : ");
lake_time = scanner.nextLine();
time.add(lake_time);
//I'm doing this just in case my user does not enter a number
System.out.println("Do you want add another lake : \"Y\" for Yes OR another key to see the statistic the problem ");
answer = scanner.nextLine();
} while (answer.equalsIgnoreCase("Y"));
//We can continue here to do more stuff
for (int i = 0; i < name.size(); i++) {
putObjects(test_01, name.get(i), time.get(i));
}
/*Collection<String> x = test_01.get("x");
System.out.println(x);*/
// to get unique elements
Set<String> treesetList = new TreeSet<String>(name);
// to iterate again
List<String> list = new ArrayList<> (treesetList);
for (String s : treesetList){
Collection<String> uno = test_01.get(s);
System.out.println(uno);
}
}
private static void putObjects (Map<String, List<String>> a, String key, String value) {
List<String> myClassList = a.get(key);
if(myClassList == null) {
myClassList = new ArrayList<>();
a.put(key, myClassList);
}
myClassList.add(value);
}
}
我的问题在这里
for (String s : treesetList){
Collection<String> uno = test_01.get(s);
System.out.println(uno);
}
因为我必须在&#34; test_01&#34;中访问不同的湖名称及其集合。从地图...我不知道如何保存到具有不同名称(或创建它们)的不同数组,以便我可以检查它的时间....我将把集合转换为&#34; double&#34;后来...
答案 0 :(得分:0)
创建集合,然后使用add。
List<String> aList = new ArrayList<String>();
for (String s : treesetList){
aList.add(test_01.get(s));
}
for (String str : aList){
System.out.println(str);
}