Related Topics

JAVA Programming
import java.util.Collections;
Create a collection of elements that you want to sort. For example, if you have an ArrayList of integers, you can create it like this:
List<Integer> numbers = new ArrayList<>();
numbers.add(4);
numbers.add(2);
numbers.add(6);
numbers.add(1);
Call the sort() method on the collection, passing it as an argument:
Collections.sort(numbers);
The collection will be sorted in ascending order by default. If you want to sort it in descending order, you can use the reverseOrder() method from the Collections class:
Collections.sort(numbers, Collections.reverseOrder());
If you have a collection of custom objects, you can implement the Comparable interface in the object class and override the compareTo() method to specify how the objects should be compared during sorting.
For example, if you have a collection of Person objects and you want to sort them by age, you can implement the Comparable interface in the Person class and override the compareTo() method like this:
public class Person implements Comparable<Person> {
private int age;
// Other attributes and methods...
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age);
}
}
Then, you can sort a collection of Person objects like this:
List<Person> people = new ArrayList<>();
// Add some Person objects to the list...
Collections.sort(people);
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
int value = map.get("banana"); // returns 2
And here is an example of how to use a Hashtable:
Map<String, Integer> map = new Hashtable<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
int value = map.get("banana"); // returns 2
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("cherry");
set.add("apple"); // not added, because "apple" already exists in the Set
You can also use the contains() method to check if an element exists in the Set:
boolean exists = set.contains("banana"); // returns true
And you can remove an element from the Set using the remove() method:
set.remove("cherry");




Popular Category
Topics for You
Go through our study material. Your Job is awaiting.