I am trying to print out all the elements of a List
, however it is printing the pointer of the Object
rather than the value.
我正在尝试打印列表的所有元素,但是它打印的是对象的指针而不是值。
This is my printing code...
这是我的打印代码……
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
Could anyone please help me why it isn't printing the value of the elements.
谁能告诉我为什么它不打印元素的值?
17 个解决方案
#1
81
Here is some example about getting print out the list component:
下面是打印列表组件的一些例子:
public class ListExample {
public static void main(String[] args) {
List<Model> models = new ArrayList<>();
// TODO: First create your model and add to models ArrayList, to prevent NullPointerException for trying this example
// Print the name from the list....
for(Model model : models) {
System.out.println(model.getName());
}
// Or like this...
for(int i = 0; i < models.size(); i++) {
System.out.println(models.get(i).getName());
}
}
}
class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#2
326
The following is compact and avoids the loop in your example code (and gives you nice commas):
以下内容紧凑,避免了示例代码中的循环(并提供了很好的逗号):
System.out.println(Arrays.toString(list.toArray()));
However, as others have pointed out, if you don't have sensible toString() methods implemented for the objects inside the list, you will get the object pointers (hash codes, in fact) you're observing. This is true whether they're in a list or not.
然而,正如其他人所指出的,如果您没有为列表中的对象实现的合理的toString()方法,那么您将获得您正在观察的对象指针(实际上是散列代码)。无论它们是否在列表中,这都是正确的。
#3
73
Since Java 8, List inherits a default "forEach" method which you can combine with the method reference "System.out::println" like this:
由于Java 8, List继承了一个默认的“forEach”方法,您可以将它与方法引用“System”结合使用。::println”是这样的:
list.forEach(System.out::println);
#4
22
System.out.println(list);//toString() is easy and good enough for debugging.
toString()
of AbstractCollection
will be clean and easy enough to do that. AbstractList
is a subclass of AbstractCollection
, so no need to for loop and no toArray() needed.
AbstractCollection的toString()将非常干净和容易做到这一点。AbstractList是AbstractCollection的子类,因此不需要循环,也不需要toArray()。
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
返回此集合的字符串表示形式。字符串表示由集合元素的列表组成,其迭代器按其返回的顺序返回这些元素,并以方括号括起来(“[]”)。相邻的元素由字符“,”(逗号和空格)分隔。元素通过String.valueOf(对象)转换为字符串。
If you are using any custom object in your list, say Student , you need to override its toString()
method(it is always good to override this method) to have a meaningful output
如果您正在使用列表中的任何自定义对象,例如Student,您需要重写它的toString()方法(重写此方法总是好的)以获得有意义的输出
See the below example:
看下面的例子:
public class TestPrintElements {
public static void main(String[] args) {
//Element is String, Integer,or other primitive type
List<String> sList = new ArrayList<String>();
sList.add("string1");
sList.add("string2");
System.out.println(sList);
//Element is custom type
Student st1=new Student(15,"Tom");
Student st2=new Student(16,"Kate");
List<Student> stList=new ArrayList<Student>();
stList.add(st1);
stList.add(st2);
System.out.println(stList);
}
}
public class Student{
private int age;
private String name;
public Student(int age, String name){
this.age=age;
this.name=name;
}
@Override
public String toString(){
return "student "+name+", age:" +age;
}
}
output:
输出:
[string1, string2]
[student Tom age:15, student Kate age:16]
#5
18
The Java 8 Streams approach...
Java 8 Streams方法…
list.stream().forEach(System.out::println);
#6
13
The objects in the list must have toString
implemented for them to print something meaningful to screen.
列表中的对象必须实现字符串,以便打印有意义的内容到屏幕上。
Here's a quick test to see the differences:
下面是一个快速测试,看看它们的区别:
public class Test {
public class T1 {
public Integer x;
}
public class T2 {
public Integer x;
@Override
public String toString() {
return x.toString();
}
}
public void run() {
T1 t1 = new T1();
t1.x = 5;
System.out.println(t1);
T2 t2 = new T2();
t2.x = 5;
System.out.println(t2);
}
public static void main(String[] args) {
new Test().run();
}
}
And when this executes, the results printed to screen are:
当执行此操作时,打印到屏幕的结果是:
t1 = Test$T1@19821f
t2 = 5
Since T1 does not override the toString method, its instance t1 prints out as something that isn't very useful. On the other hand, T2 overrides toString, so we control what it prints when it is used in I/O, and we see something a little better on screen.
由于T1没有覆盖toString方法,因此它的实例T1输出为一些不太有用的东西。另一方面,T2覆盖了toString,所以当它在I/O中使用时,我们控制了它打印的内容,我们在屏幕上看到了一些更好的东西。
#7
8
By using java 8 features.
通过使用java 8特性。
import java.util.Arrays;
import java.util.List;
/**
* @author AJMAL SHA
*
*/
public class ForEach {
public static void main(String[] args) {
List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
(features).forEach(System.out::println);
}
}
#8
5
- You haven't specified what kind of elements the list contains, if it is a primitive data type then you can print out the elements.
- 您还没有指定列表包含的元素类型,如果它是原始数据类型,那么您可以打印出元素。
-
But if the elements are objects then as Kshitij Mehta mentioned you need to implement (override) the method "toString" within that object - if it is not already implemented - and let it return something meaning full from within the object, example:
但是,如果元素是对象,那么就像Kshitij Mehta提到的那样,你需要在对象中实现(覆盖)方法“toString”——如果它还没有实现——并让它从对象中返回一些有意义的东西,例如:
class Person { private String firstName; private String lastName; @Override public String toString() { return this.firstName + " " + this.lastName; } }
#9
4
Consider a List<String> stringList
which can be printed in many ways using Java 8 constructs:
考虑一个列表
stringList.forEach(System.out::println); // 1) Iterable.forEach
stringList.stream().forEach(System.out::println); // 2) Stream.forEach (order maintained generally but doc does not guarantee)
stringList.stream().forEachOrdered(System.out::println); // 3) Stream.forEachOrdered (order maintained always)
stringList.parallelStream().forEach(System.out::println); // 4) Parallel version of Stream.forEach (order not maintained)
stringList.parallelStream().forEachOrdered(System.out::println); // 5) Parallel version ofStream.forEachOrdered (order maintained always)
How are these approaches different from each other?
First Approach (Iterable.forEach
)- The iterator of the collection is generally used and that is designed to be fail-fast which means it will throw ConcurrentModificationException
if the underlying collection is structurally modified during the iteration. As mentioned in the doc for ArrayList
:
第一种方法(Iterable.forEach)——通常使用集合的迭代器,它被设计成快速失败,这意味着如果底层集合在迭代期间被结构修改,它将抛出ConcurrentModificationException。正如ArrayList的doc中提到的:
A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.
结构修改是任何添加或删除一个或多个元素或显式调整支持数组大小的操作;仅仅设置元素的值并不是结构性修改。
So it means for ArrayList.forEach
setting the value is allowed without any issue. And in case of concurrent collection e.g. ConcurrentLinkedQueue
the iterator would be weakly-consistent which means the actions passed in forEach
are allowed to make even structural changes without ConcurrentModificationException
exception being thrown. But here the modifications might or might not be visible in that iteration.
它表示ArrayList。对于每个设置,值是允许的,没有任何问题。对于并发集合,例如ConcurrentLinkedQueue,迭代器将是弱一致的,这意味着传递给forEach的操作可以在不抛出ConcurrentModificationExceptionexception的情况下进行结构更改。但是这里的修改可能在迭代中可见,也可能不可见。
Second Approach (Stream.forEach
)- The order is undefined. Though it may not occur for sequential streams but the specification does not guarantee it. Also the action is required to be non-interfering in nature. As mentioned in doc:
第二种方法(Stream.forEach)——顺序没有定义。虽然它可能不会发生在顺序流中,但是规范并不能保证它。而且这种行为必须是不干涉自然的。道格:所
The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.
此操作的行为显式不确定性。对于并行流管道,此操作不能保证尊重流的遇到顺序,因为这样做会牺牲并行性的好处。
Third Approach (Stream.forEachOrdered
)- The action would be performed in the encounter order of the stream. So whenever order matters use forEachOrdered
without a second thought. As mentioned in the doc:
第三种方法(流。foreachordered)——操作将按照流的遇到顺序执行。所以,无论什么时候,只要秩序重要,就不用再想了。正如《doc》中提到的:
Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.
如果流具有定义的相遇顺序,则按照流的相遇顺序对流的每个元素执行操作。
While iterating over a synchronized collection the first approach would take the collection's lock once and would hold it across all the calls to action method, but in case of streams they use collection's spliterator, which does not lock and relies on the already established rules of non-interference. In case collection backing the stream is modified during iteration a ConcurrentModificationException
would be thrown or inconsistent result may occur.
在对同步集合进行迭代时,第一个方法将会对集合的锁进行一次处理,并在所有调用操作方法的调用中保留它,但是在流的情况下,它们使用集合的spliterator,它不会锁定并依赖于已经建立的不受干扰的规则。如果在迭代过程中修改了支持流的集合,就会抛出ConcurrentModificationException,或者可能出现不一致的结果。
Fourth Approach (Parallel Stream.forEach
)- As already mentioned no guarantee to respect the encounter order as expected in case of parallel streams. It is possible that action is performed in different thread for different elements which can never be the case with forEachOrdered
.
第四种方法(并行流。foreach)——正如前面提到的,在并行流的情况下,没有保证会遵守预期的顺序。对于不同的元素,可以在不同的线程中执行操作,而对于forEachOrdered元素则不可能这样。
Fifth Approach (Parallel Stream.forEachOrdered
)- The forEachOrdered
will process the elements in the order specified by the source irrespective of the fact whether stream is sequential or parallel. So it makes no sense to use this with parallel streams.
第五种方法(并行流.forEachOrdered)- forEachOrdered将按照源指定的顺序处理元素,不管流是连续的还是并行的。所以使用并行流是没有意义的。
#10
2
I wrote a dump function, which basicly prints out the public members of an object if it has not overriden toString(). One could easily expand it to call getters. Javadoc:
我编写了一个dump函数,如果对象没有overriden toString(),那么该函数将打印出该对象的公共成员。我们可以很容易地将其扩展为getters。Javadoc:
Dumps an given Object to System.out, using the following rules:
将给定的对象转储到系统。外,使用以下规则:
- If the Object is Iterable, all of its components are dumped.
- 如果对象是可迭代的,那么它的所有组件都将被转储。
- If the Object or one of its superclasses overrides toString(), the "toString" is dumped
- 如果对象或它的一个超类覆盖toString(),那么“toString”将被转储
- Else the method is called recursively for all public members of the Object
- 否则,对对象的所有公共成员递归地调用该方法
/**
* Dumps an given Object to System.out, using the following rules:<br>
* <ul>
* <li> If the Object is {@link Iterable}, all of its components are dumped.</li>
* <li> If the Object or one of its superclasses overrides {@link #toString()}, the "toString" is dumped</li>
* <li> Else the method is called recursively for all public members of the Object </li>
* </ul>
* @param input
* @throws Exception
*/
public static void dump(Object input) throws Exception{
dump(input, 0);
}
private static void dump(Object input, int depth) throws Exception{
if(input==null){
System.out.print("null\n"+indent(depth));
return;
}
Class<? extends Object> clazz = input.getClass();
System.out.print(clazz.getSimpleName()+" ");
if(input instanceof Iterable<?>){
for(Object o: ((Iterable<?>)input)){
System.out.print("\n"+indent(depth+1));
dump(o, depth+1);
}
}else if(clazz.getMethod("toString").getDeclaringClass().equals(Object.class)){
Field[] fields = clazz.getFields();
if(fields.length == 0){
System.out.print(input+"\n"+indent(depth));
}
System.out.print("\n"+indent(depth+1));
for(Field field: fields){
Object o = field.get(input);
String s = "|- "+field.getName()+": ";
System.out.print(s);
dump(o, depth+1);
}
}else{
System.out.print(input+"\n"+indent(depth));
}
}
private static String indent(int depth) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<depth; i++)
sb.append(" ");
return sb.toString();
}
#11
2
Or you could simply use the Apache Commons utilities:
或者您可以使用Apache Commons实用程序:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ArrayUtils.html # toString-java.lang.Object -
List<MyObject> myObjects = ...
System.out.println(ArrayUtils.toString(myObjects));
#12
1
System.out.println(list);
works for me.
System.out.println(列表);为我工作。
Here is a full example:
这里有一个完整的例子:
import java.util.List;
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
final List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
System.out.println(list);
}
}
It will print [Hello, World]
.
它会打印[你好,世界]。
#13
1
list.stream().map(x -> x.getName()).forEach(System.out::println);
#14
0
For a list of array of String
用于字符串数组的列表
list.forEach(s -> System.out.println(Arrays.toString((String[]) s )));
#15
0
try to override toString() method as you want that the element will be printend. so the method to print can be this:
尝试重写toString()方法,只要您希望元素是printend。所以打印的方法是这样的:
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).toString());
}
#16
-1
List<String> textList= messageList.stream()
.map(Message::getText)
.collect(Collectors.toList());
textList.stream().forEach(System.out::println);
public class Message {
String name;
String text;
public Message(String name, String text) {
this.name = name;
this.text = text;
}
public String getName() {
return name;
}
public String getText() {
return text;
}
}
#17
-1
public static void main(String[] args) {
answer(10,60);
}
public static void answer(int m,int k){
AtomicInteger n = new AtomicInteger(m);
Stream<Integer> stream = Stream.generate(() -> n.incrementAndGet()).limit(k);
System.out.println(Arrays.toString(stream.toArray()));
}
#1
81
Here is some example about getting print out the list component:
下面是打印列表组件的一些例子:
public class ListExample {
public static void main(String[] args) {
List<Model> models = new ArrayList<>();
// TODO: First create your model and add to models ArrayList, to prevent NullPointerException for trying this example
// Print the name from the list....
for(Model model : models) {
System.out.println(model.getName());
}
// Or like this...
for(int i = 0; i < models.size(); i++) {
System.out.println(models.get(i).getName());
}
}
}
class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#2
326
The following is compact and avoids the loop in your example code (and gives you nice commas):
以下内容紧凑,避免了示例代码中的循环(并提供了很好的逗号):
System.out.println(Arrays.toString(list.toArray()));
However, as others have pointed out, if you don't have sensible toString() methods implemented for the objects inside the list, you will get the object pointers (hash codes, in fact) you're observing. This is true whether they're in a list or not.
然而,正如其他人所指出的,如果您没有为列表中的对象实现的合理的toString()方法,那么您将获得您正在观察的对象指针(实际上是散列代码)。无论它们是否在列表中,这都是正确的。
#3
73
Since Java 8, List inherits a default "forEach" method which you can combine with the method reference "System.out::println" like this:
由于Java 8, List继承了一个默认的“forEach”方法,您可以将它与方法引用“System”结合使用。::println”是这样的:
list.forEach(System.out::println);
#4
22
System.out.println(list);//toString() is easy and good enough for debugging.
toString()
of AbstractCollection
will be clean and easy enough to do that. AbstractList
is a subclass of AbstractCollection
, so no need to for loop and no toArray() needed.
AbstractCollection的toString()将非常干净和容易做到这一点。AbstractList是AbstractCollection的子类,因此不需要循环,也不需要toArray()。
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
返回此集合的字符串表示形式。字符串表示由集合元素的列表组成,其迭代器按其返回的顺序返回这些元素,并以方括号括起来(“[]”)。相邻的元素由字符“,”(逗号和空格)分隔。元素通过String.valueOf(对象)转换为字符串。
If you are using any custom object in your list, say Student , you need to override its toString()
method(it is always good to override this method) to have a meaningful output
如果您正在使用列表中的任何自定义对象,例如Student,您需要重写它的toString()方法(重写此方法总是好的)以获得有意义的输出
See the below example:
看下面的例子:
public class TestPrintElements {
public static void main(String[] args) {
//Element is String, Integer,or other primitive type
List<String> sList = new ArrayList<String>();
sList.add("string1");
sList.add("string2");
System.out.println(sList);
//Element is custom type
Student st1=new Student(15,"Tom");
Student st2=new Student(16,"Kate");
List<Student> stList=new ArrayList<Student>();
stList.add(st1);
stList.add(st2);
System.out.println(stList);
}
}
public class Student{
private int age;
private String name;
public Student(int age, String name){
this.age=age;
this.name=name;
}
@Override
public String toString(){
return "student "+name+", age:" +age;
}
}
output:
输出:
[string1, string2]
[student Tom age:15, student Kate age:16]
#5
18
The Java 8 Streams approach...
Java 8 Streams方法…
list.stream().forEach(System.out::println);
#6
13
The objects in the list must have toString
implemented for them to print something meaningful to screen.
列表中的对象必须实现字符串,以便打印有意义的内容到屏幕上。
Here's a quick test to see the differences:
下面是一个快速测试,看看它们的区别:
public class Test {
public class T1 {
public Integer x;
}
public class T2 {
public Integer x;
@Override
public String toString() {
return x.toString();
}
}
public void run() {
T1 t1 = new T1();
t1.x = 5;
System.out.println(t1);
T2 t2 = new T2();
t2.x = 5;
System.out.println(t2);
}
public static void main(String[] args) {
new Test().run();
}
}
And when this executes, the results printed to screen are:
当执行此操作时,打印到屏幕的结果是:
t1 = Test$T1@19821f
t2 = 5
Since T1 does not override the toString method, its instance t1 prints out as something that isn't very useful. On the other hand, T2 overrides toString, so we control what it prints when it is used in I/O, and we see something a little better on screen.
由于T1没有覆盖toString方法,因此它的实例T1输出为一些不太有用的东西。另一方面,T2覆盖了toString,所以当它在I/O中使用时,我们控制了它打印的内容,我们在屏幕上看到了一些更好的东西。
#7
8
By using java 8 features.
通过使用java 8特性。
import java.util.Arrays;
import java.util.List;
/**
* @author AJMAL SHA
*
*/
public class ForEach {
public static void main(String[] args) {
List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
(features).forEach(System.out::println);
}
}
#8
5
- You haven't specified what kind of elements the list contains, if it is a primitive data type then you can print out the elements.
- 您还没有指定列表包含的元素类型,如果它是原始数据类型,那么您可以打印出元素。
-
But if the elements are objects then as Kshitij Mehta mentioned you need to implement (override) the method "toString" within that object - if it is not already implemented - and let it return something meaning full from within the object, example:
但是,如果元素是对象,那么就像Kshitij Mehta提到的那样,你需要在对象中实现(覆盖)方法“toString”——如果它还没有实现——并让它从对象中返回一些有意义的东西,例如:
class Person { private String firstName; private String lastName; @Override public String toString() { return this.firstName + " " + this.lastName; } }
#9
4
Consider a List<String> stringList
which can be printed in many ways using Java 8 constructs:
考虑一个列表
stringList.forEach(System.out::println); // 1) Iterable.forEach
stringList.stream().forEach(System.out::println); // 2) Stream.forEach (order maintained generally but doc does not guarantee)
stringList.stream().forEachOrdered(System.out::println); // 3) Stream.forEachOrdered (order maintained always)
stringList.parallelStream().forEach(System.out::println); // 4) Parallel version of Stream.forEach (order not maintained)
stringList.parallelStream().forEachOrdered(System.out::println); // 5) Parallel version ofStream.forEachOrdered (order maintained always)
How are these approaches different from each other?
First Approach (Iterable.forEach
)- The iterator of the collection is generally used and that is designed to be fail-fast which means it will throw ConcurrentModificationException
if the underlying collection is structurally modified during the iteration. As mentioned in the doc for ArrayList
:
第一种方法(Iterable.forEach)——通常使用集合的迭代器,它被设计成快速失败,这意味着如果底层集合在迭代期间被结构修改,它将抛出ConcurrentModificationException。正如ArrayList的doc中提到的:
A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.
结构修改是任何添加或删除一个或多个元素或显式调整支持数组大小的操作;仅仅设置元素的值并不是结构性修改。
So it means for ArrayList.forEach
setting the value is allowed without any issue. And in case of concurrent collection e.g. ConcurrentLinkedQueue
the iterator would be weakly-consistent which means the actions passed in forEach
are allowed to make even structural changes without ConcurrentModificationException
exception being thrown. But here the modifications might or might not be visible in that iteration.
它表示ArrayList。对于每个设置,值是允许的,没有任何问题。对于并发集合,例如ConcurrentLinkedQueue,迭代器将是弱一致的,这意味着传递给forEach的操作可以在不抛出ConcurrentModificationExceptionexception的情况下进行结构更改。但是这里的修改可能在迭代中可见,也可能不可见。
Second Approach (Stream.forEach
)- The order is undefined. Though it may not occur for sequential streams but the specification does not guarantee it. Also the action is required to be non-interfering in nature. As mentioned in doc:
第二种方法(Stream.forEach)——顺序没有定义。虽然它可能不会发生在顺序流中,但是规范并不能保证它。而且这种行为必须是不干涉自然的。道格:所
The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.
此操作的行为显式不确定性。对于并行流管道,此操作不能保证尊重流的遇到顺序,因为这样做会牺牲并行性的好处。
Third Approach (Stream.forEachOrdered
)- The action would be performed in the encounter order of the stream. So whenever order matters use forEachOrdered
without a second thought. As mentioned in the doc:
第三种方法(流。foreachordered)——操作将按照流的遇到顺序执行。所以,无论什么时候,只要秩序重要,就不用再想了。正如《doc》中提到的:
Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.
如果流具有定义的相遇顺序,则按照流的相遇顺序对流的每个元素执行操作。
While iterating over a synchronized collection the first approach would take the collection's lock once and would hold it across all the calls to action method, but in case of streams they use collection's spliterator, which does not lock and relies on the already established rules of non-interference. In case collection backing the stream is modified during iteration a ConcurrentModificationException
would be thrown or inconsistent result may occur.
在对同步集合进行迭代时,第一个方法将会对集合的锁进行一次处理,并在所有调用操作方法的调用中保留它,但是在流的情况下,它们使用集合的spliterator,它不会锁定并依赖于已经建立的不受干扰的规则。如果在迭代过程中修改了支持流的集合,就会抛出ConcurrentModificationException,或者可能出现不一致的结果。
Fourth Approach (Parallel Stream.forEach
)- As already mentioned no guarantee to respect the encounter order as expected in case of parallel streams. It is possible that action is performed in different thread for different elements which can never be the case with forEachOrdered
.
第四种方法(并行流。foreach)——正如前面提到的,在并行流的情况下,没有保证会遵守预期的顺序。对于不同的元素,可以在不同的线程中执行操作,而对于forEachOrdered元素则不可能这样。
Fifth Approach (Parallel Stream.forEachOrdered
)- The forEachOrdered
will process the elements in the order specified by the source irrespective of the fact whether stream is sequential or parallel. So it makes no sense to use this with parallel streams.
第五种方法(并行流.forEachOrdered)- forEachOrdered将按照源指定的顺序处理元素,不管流是连续的还是并行的。所以使用并行流是没有意义的。
#10
2
I wrote a dump function, which basicly prints out the public members of an object if it has not overriden toString(). One could easily expand it to call getters. Javadoc:
我编写了一个dump函数,如果对象没有overriden toString(),那么该函数将打印出该对象的公共成员。我们可以很容易地将其扩展为getters。Javadoc:
Dumps an given Object to System.out, using the following rules:
将给定的对象转储到系统。外,使用以下规则:
- If the Object is Iterable, all of its components are dumped.
- 如果对象是可迭代的,那么它的所有组件都将被转储。
- If the Object or one of its superclasses overrides toString(), the "toString" is dumped
- 如果对象或它的一个超类覆盖toString(),那么“toString”将被转储
- Else the method is called recursively for all public members of the Object
- 否则,对对象的所有公共成员递归地调用该方法
/**
* Dumps an given Object to System.out, using the following rules:<br>
* <ul>
* <li> If the Object is {@link Iterable}, all of its components are dumped.</li>
* <li> If the Object or one of its superclasses overrides {@link #toString()}, the "toString" is dumped</li>
* <li> Else the method is called recursively for all public members of the Object </li>
* </ul>
* @param input
* @throws Exception
*/
public static void dump(Object input) throws Exception{
dump(input, 0);
}
private static void dump(Object input, int depth) throws Exception{
if(input==null){
System.out.print("null\n"+indent(depth));
return;
}
Class<? extends Object> clazz = input.getClass();
System.out.print(clazz.getSimpleName()+" ");
if(input instanceof Iterable<?>){
for(Object o: ((Iterable<?>)input)){
System.out.print("\n"+indent(depth+1));
dump(o, depth+1);
}
}else if(clazz.getMethod("toString").getDeclaringClass().equals(Object.class)){
Field[] fields = clazz.getFields();
if(fields.length == 0){
System.out.print(input+"\n"+indent(depth));
}
System.out.print("\n"+indent(depth+1));
for(Field field: fields){
Object o = field.get(input);
String s = "|- "+field.getName()+": ";
System.out.print(s);
dump(o, depth+1);
}
}else{
System.out.print(input+"\n"+indent(depth));
}
}
private static String indent(int depth) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<depth; i++)
sb.append(" ");
return sb.toString();
}
#11
2
Or you could simply use the Apache Commons utilities:
或者您可以使用Apache Commons实用程序:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ArrayUtils.html # toString-java.lang.Object -
List<MyObject> myObjects = ...
System.out.println(ArrayUtils.toString(myObjects));
#12
1
System.out.println(list);
works for me.
System.out.println(列表);为我工作。
Here is a full example:
这里有一个完整的例子:
import java.util.List;
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
final List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
System.out.println(list);
}
}
It will print [Hello, World]
.
它会打印[你好,世界]。
#13
1
list.stream().map(x -> x.getName()).forEach(System.out::println);
#14
0
For a list of array of String
用于字符串数组的列表
list.forEach(s -> System.out.println(Arrays.toString((String[]) s )));
#15
0
try to override toString() method as you want that the element will be printend. so the method to print can be this:
尝试重写toString()方法,只要您希望元素是printend。所以打印的方法是这样的:
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).toString());
}
#16
-1
List<String> textList= messageList.stream()
.map(Message::getText)
.collect(Collectors.toList());
textList.stream().forEach(System.out::println);
public class Message {
String name;
String text;
public Message(String name, String text) {
this.name = name;
this.text = text;
}
public String getName() {
return name;
}
public String getText() {
return text;
}
}
#17
-1
public static void main(String[] args) {
answer(10,60);
}
public static void answer(int m,int k){
AtomicInteger n = new AtomicInteger(m);
Stream<Integer> stream = Stream.generate(() -> n.incrementAndGet()).limit(k);
System.out.println(Arrays.toString(stream.toArray()));
}