[英]Java print List and arraylist
I was hoping someone could help me out with a small problem I am having in java. 我希望有人可以帮助我解决我在java中遇到的一个小问题。 I have a List and an ArrayList that I would like to output to a file with the first element of each, printed next to one another.
我有一个List和一个ArrayList,我想输出到一个文件,每个文件的第一个元素,彼此相邻打印。 Here is what I have so far:
这是我到目前为止:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for(String unique:uniqueList){
out.write(unique + "\r");
}
ArrayList<Integer>subtr=new ArrayList<Integer>();
out.write("The number: " + subtr + "\r");
This results in this output: 这导致了这个输出:
A
B
C
D
E
F
The number: [1, 2, 3, 4, 5, 6]
But I would rather it be like this: 但我宁愿这样:
A The number: 1
B The number: 2
...etc. ...等等。
I am not really sure where to start on how to get the output format like that. 我不确定从哪里开始如何获得这样的输出格式。 I tried putting both sets of values into arrays but I just ended up confusing myself... Which is how I ended up here.
我尝试将两组值都放入数组中,但我最终让自己感到困惑......这就是我最终的结果。 Any help would be super appreciated.
任何帮助将非常感激。
Simply do this: 只需这样做:
String br = System.getProperty("line.separator");
for (int i = 0, n = Math.min(uniqueList.size(), subtr.size()); i < n; i++)
out.write(uniqueList.get(i) + " The number: " + subtr.get(i) + br);
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<Integer>subtr=new ArrayList<Integer>();
for (int i = 0; i < uniqueList.size(); i++){
out.write(uniqueList.get(i) + "\r");
out.write("The number: " + subtr.get(i) + "\n");
}
NOTE : This assumes that both lists have the same number of elements. 注意 :这假定两个列表具有相同数量的元素。 If they are not, you would iterate to
Math.min(uniqueList.size(), subtr.size())
. 如果不是,则迭代到
Math.min(uniqueList.size(), subtr.size())
。
This should do it: 这应该这样做:
int maxLength = Math.min(uniqueList.size(), subtr.size());
for(int i = 0; i < maxLength; i++)
{
out.print(uniqueList.get(i) + " The number: " + subtr.get(i) + "\r");
}
Something like this: 像这样的东西:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<Integer> subtr = new ArrayList<Integer>();
int length = Math.min(uniqueList.size(), substr.size());
for (int i = 0; i < length; i++) {
out.write(uniqueList.get(i) + " The number: " + substr.get(i) + "\r");
}
The efficient way is to maintain a HashMap
with uniqueList
as keys and subtr
as values. 有效的方法是维护一个
HashMap
其中uniqueList
作为键, subtr
作为值。 Then iterate over a map. 然后遍历地图。
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i = 0; i < uniqueList.size(); i++){
map.put(key, subtr.get(i));
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
out.println(entry.getKey() + " The Number : " + entry.getValue());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.