Some important techniques
- Eclipse: Oxygen
- Java: 1.8
The tutorial shows some important techniques that can be implemented and that save time, for example. The addAll() Â method for queues and sets and also implementing the binary search in the same also explore the comparable interface for lists.
The following program demonstrates how to create a list from set items. As this list is created from the set, so duplicate items will be eliminated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class App { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Chaand"); set.add("John"); set.add("Aafiya"); set.add("Armaan"); set.add("Mia"); set.add("chaand"); List<String> list = new ArrayList<>(); list.addAll(set); for (String name : list) { System.out.println(name); } } } |
Output
Chaand
Mia
Armaan
John
Aafiya
We can also apply some more collection functions to the list. Like we can sort the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class App { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Chaand"); set.add("John"); set.add("Aafiya"); set.add("Armaan"); set.add("Mia"); set.add("Chaand"); List<String> list = new ArrayList<>(); list.addAll(set); Collections.sort(list); for (String name : list) { System.out.println(name); } } } |
Output
Aafiya
Armaan
Chaand
John
Mia.
We can search for any element in a list using binarySearch() method. if the element is present in the collection, binarySearch() method return the index position of the element. If the element is not present, binarySearch() returns the negative value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class App { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Chaand"); set.add("John"); set.add("Aafiya"); set.add("Armaan"); set.add("Mia"); set.add("Chaand"); List<String> list = new ArrayList<>(); list.addAll(set); Collections.sort(list); for (String name : list) { System.out.println(name); } System.out.println(Collections.binarySearch(list, "test")); } } |
Output
Aafiya
Armaan
Chaand
John
Mia
-6
Contributed by Poonam Tomar