I was hoping someone could help me out with a small problem I am having in 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. 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())
.
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. 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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.