How to Print Out All the Elements of a List in Java

How to print out all the elements of a List in Java?

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;
}
}

Simple way to print List(String[]) Java

The code of the other answer would print something like:

[[Ljava.lang.String;@4c873330, [Ljava.lang.String;@119d7047]

What you need is either:

rows.forEach(arr -> System.out.println(Arrays.toString(arr)));

which would print the output like this:

[a, b, c]
[d, e, f]

or

System.out.println(Arrays.deepToString(rows.toArray()));

which would print the output like this:

[[a, b, c], [d, e, f]]

Java - print a List<>

first go to your Item class, and @override the toString() method, after that, you can go through the list and print it:

System.out.print("[");
for(Item it : myListOfItems) {
System.out.print(it.toString() + ", ");
}
System.out.print("]");

Print all arraylist items in one row if they are not empty Java

You can extract a sublist based on indices and form the output string.

List<String> items = List.of("0500123;0501023;050100".split(";"));
int printFirstN = 2;

String c = String.join(" ", items.subList(0, printFirstN));
System.out.println(c);

Output: 0500123 0501023

print all the content in a "node list" on the same line

Use System.out.print() instead of System.out.println():

public void escrevePolinomio (Node lista){
if(lista != null){
System.out.print(lista.getElement().getCoef()+"x^"+lista.getElement().getExp());
lista=lista.getnext();
escrevePolinomio(lista);
}
}


Related Topics



Leave a reply



Submit