AndroidPub
Published in

AndroidPub

A Comparison of Performances between TreeMap and PriorityQueue in One Use Case

Use Case

{480, "url_for_w480"}
{768, "url_for_w768"}
{1280, "url_for_w1280"}
{1920, "url_for_w1920"}
final int screenWidth = Device.getScreenWidth();
{768, "url_for_w768"}
{1280, "url_for_w1280"}

Problem

{768, "url_for_w768"}
{1920, "url_for_w1920"}
{480, "url_for_w480"}
{1280, "url_for_w1280"}

Solutions

  1. TreeMap
  2. PriorityQueue

TreeMap

  1. put all entries into a TreeMap and they will be sorted;
  2. iterate from the beginning to the last entry, whenever an image whose width is larger than the screen width is found, return its URL;
  3. If none of the images’ widths is larger than the screen width, use the last entry’s URL, which has the highest resolution.

PriorityQueue

  1. enqueue all entries into a PriorityQueue;
  2. poll from the front of the PriorityQueue until there is only one entry left in the queue; whenever an image whose width is larger than the screen width is found, return its URL;
  3. If none of the previous images’ widths is larger than the screen width, use the last entry’s URL, which has the highest resolution.

Conclusion

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store