Join Regular Classroom : Visit ClassroomTech

JAVA – codewindow.in

Related Topics

JAVA Programming

// create a priority queue with custom comparator
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

// add elements to the priority queue
pq.add(5);
pq.add(3);
pq.add(10);

// remove and print elements from the priority queue
while (!pq.isEmpty()) {
    System.out.println(pq.poll());
}

This will output:

10
5
3

In this example, we create a PriorityQueue with a custom comparator that orders elements in reverse order. We add three integers to the queue and then remove them using the poll() method, which removes and returns the highest priority element. The elements are printed in reverse order because of the custom comparator.

// create a LinkedHashMap
LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();

// add elements to the LinkedHashMap
lhm.put("one", 1);
lhm.put("two", 2);
lhm.put("three", 3);

// iterate over the LinkedHashMap
for (Map.Entry<String, Integer> entry : lhm.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

This will output:

one = 1
two = 2
three = 3

In this example, we create a LinkedHashMap and add three key-value pairs to it in order. We then iterate over the LinkedHashMap using an enhanced for loop over the entry set, which will iterate over the elements in the order of insertion. We print out each key-value pair using the getKey() and getValue() methods of the Map.Entry interface. The output shows that the order of iteration matches the order of insertion.

      

Go through our study material. Your Job is awaiting.

Recent Posts
Categories