Related Topics

JAVA Programming
// create a new LinkedHashSet
Set<String> linkedHashSet = new LinkedHashSet<>();
// add elements to the LinkedHashSet
linkedHashSet.add("apple");
linkedHashSet.add("banana");
linkedHashSet.add("orange");
// print the contents of the LinkedHashSet
System.out.println(linkedHashSet); // prints [apple, banana, orange]
In this example, the LinkedHashSet
maintains the order in which the elements were added ("apple"
, "banana"
, "orange"
) and prints them out in that order.
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Alice", 20);
treeMap.put("Bob", 25);
treeMap.put("Charlie", 30);
treeMap.put("David", 35);
In this example, the keys are of type String and the values are of type Integer. The elements are added to the TreeMap using the put() method. The TreeMap will automatically sort the keys in alphabetical order.
You can also create a TreeMap with a custom Comparator to sort the keys in a specific order. Here’s an example:
Comparator<String> comparator = new Comparator<String>() {
public int compare(String s1, String s2) {
return s2.compareTo(s1);
}
};
TreeMap<String, Integer> treeMap = new TreeMap<>(comparator);
treeMap.put("Alice", 20);
treeMap.put("Bob", 25);
treeMap.put("Charlie", 30);
treeMap.put("David", 35);
In this example, the keys are sorted in reverse alphabetical order based on the custom Comparator.




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