我正在尝试遍历Objects的ArrayList。对于每个Object,我想调用它的toString()方法,然后用逗号分隔它们来连接它们。
我有一些测试代码,但它没有像我期望的那样表现。我得到的以下代码的输出是:Adam, Bob, Catherine, Dylan,
当我想要的是Adam, Bob, Catherine, Dylan
时(姓氏不应该有一个逗号继续它。)
public static void main2 (){
//ArrayList of Strings rather than Objects for simplicity
ArrayList<String> test = new ArrayList<String>(Arrays.asList("Adam", "Bob", "Catherine", "Dylan"));
String output = new String();
for (String str : test) {
output += str.toString();
output += test.iterator().hasNext() ? ", " : "";
}
System.out.println(output);
}
答案 0 :(得分:4)
,
示例:强>
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class QuickTester {
public static void main(String[] args) {
ArrayList<String> test =
new ArrayList<String>(Arrays.asList(
"Adam", "Bob", "Catherine", "Dylan"));
StringBuilder sb = new StringBuilder();
Iterator<String> stringIterator = test.iterator();
while(stringIterator.hasNext()) {
sb.append(stringIterator.next());
if(stringIterator.hasNext()) {
sb.append(", ");
}
}
System.out.println(sb.toString());
}
}
<强>输出:强>
Adam, Bob, Catherine, Dylan
在问题中,对于行
output += test.iterator().hasNext() ? ", " : "";
test.iterator()
返回指向第一个元素的迭代器hasNext()
将永远为真注意:将StringBuilder用于此类事情是件好事。 :)
答案 1 :(得分:3)
使用Java8,您可以将String.Join()
与ArrayList
Object
一起使用。
public static void main(String[] args) throws Exception {
ArrayList<MyClass> test = new ArrayList();
test.add(new MyClass("Adam", 12));
test.add(new MyClass("Bob", 17));
test.add(new MyClass("Catherine", 19));
test.add(new MyClass("Dylan", 22));
System.out.println(String.join(", ", test.stream().map(mc -> mc.Name).collect(Collectors.toList())));
}
public static class MyClass {
public String Name;
public int Age;
public MyClass(String n, int a) {
this.Name = n;
this.Age = a;
}
}
结果:
Adam, Bob, Catherine, Dylan
为什么不使用String.Join()
?
public static void main(String[] args) throws Exception {
ArrayList<String> test =
new ArrayList<String>(Arrays.asList(
"Adam", "Bob", "Catherine", "Dylan"));
System.out.println(String.join(", ", test));
}
结果:
Adam, Bob, Catherine, Dylan
答案 2 :(得分:0)
试试这个
public static void main(String[] args) {
// ArrayList of Strings rather than Objects for simplicity
ArrayList<String> test = new ArrayList<String>(Arrays.asList("Adam",
"Bob", "Catherine", "Dylan"));
int size = test.size();
String output = new String();
for (String str : test) {
output += str.toString();
output += test.lastIndexOf(str) < size - 1 ? ", " : "";
}
System.out.println(output);
}
答案 3 :(得分:0)
使用这种单线
SELECT TOP (1) WITH TIES m.*
FROM missions m
ORDER BY DATEDIFF(year, m.launchdate, m.recoverydate) DESC;