Reputation: 6388
I am playing around with the Collection API in java, and came through two different ways to print out the elements in the collection. I need to know which would be the best method to be used in any situation.
The first method is to use .toString()
method (implicitly) in Collection interface.
The second method is to use iterators and visit each element and print it out. (This code is commented)
public class Test {
static Set<String> mySet1 = new HashSet<>();
static Set<String> mySet2 = new LinkedHashSet<>();
public static void main(String[] args) {
String[] arr = {"hello","world","I","am","Tom"};
for(int i=0; i<arr.length;i++){
mySet1.add(arr[i]);
mySet2.add(arr[i]);
}
System.out.println("HashSet prinitng...");
/* Iterator iter1 = mySet1.iterator();
while(iter1.hasNext()){
System.out.println(iter1.next());
}*/
System.out.println(mySet1);
System.out.println("LinkedHashSet printing");
/*
Iterator iter2 = mySet2.iterator();
while(iter2.hasNext()){
System.out.println(iter2.next());
}*/
System.out.println(mySet2);
}
}
Which is better and why?
Upvotes: 0
Views: 214
Reputation: 95998
In Java 8, you can simply:
mySet2.forEach(System.out::println);
In earlier versions:
for (String str : mySet2)
System.out.println(str);
Upvotes: 2