{"id":2047,"date":"2010-08-31T02:46:54","date_gmt":"2010-08-31T06:46:54","guid":{"rendered":"http:\/\/www.gubatron.com\/blog\/?p=2047"},"modified":"2012-07-28T04:57:04","modified_gmt":"2012-07-28T04:57:04","slug":"map-function-in-java","status":"publish","type":"post","link":"https:\/\/www.gubatron.com\/blog\/map-function-in-java\/","title":{"rendered":"Map function in Java"},"content":{"rendered":"<p>I read on some email signature something along the lines of:<br \/>\n&#8220;If I had a dollar for every for(int i=0; i < size; i++) { ... } I've written I'd be rich\"\n\nAfter coding on Android and learning about some of the tips for performance, like\n\"With an ArrayList, a hand-written counted loop is about 3x faster\"\n\n<strong>If you do use ArrayLists a lot you<\/strong> then have that tip in the back of your head and you end up with a lot of code like the following:<\/p>\n<pre lang=\"java\" line=\"1\">\r\nList<T>; myList = ... ;\r\nint size = myList.size();\r\nfor (int i=0; i &lt; size; i++) {\r\n  T elem = myList.get(i);\r\n  \/\/do something with elem\r\n}\r\n<\/pre>\n<p>Eventually there was a moment when I said, I need a freaking map function, I&#8217;m sick of this little pattern, surprisingly I couldn&#8217;t find a map() function anywhere on the java collection framework. So I went and did this.<\/p>\n<p><strong>Warning<\/strong>: These mapping utilities are meant only for Lists with RandomAccess capabilities (.get(i) happens in constant time). Do not use with LinkedList or other lists that don&#8217;t implement RandomAccess, otherwise you&#8217;ll end up with up to O(n^2) times. Thanks to Roger Kapsi for noticing this issue. [you can now tell how much we like to use ArrayList]<\/p>\n<pre lang=\"java\" line=\"1\">\r\n\/\/what I think would be the equivalent of a lambda or closure in Python...\r\npublic interface MapFunction<T> {\r\n   public void map(T t);\r\n}\r\n<\/pre>\n<p>And then on one of my utils classes I added a static method map that looks like this:<\/p>\n<pre lang=\"java\" line=\"1\">\r\npublic static <T> void map(List<T> list, MapFunction<T> mapFunction) {\r\nint size=list.size();\r\n   for (int i=0; i < size; i++) {\r\n      mapFunction.map(list.get(i));\r\n   }\r\n}\r\n<\/pre>\n<p>So now, everytime I need to iterate over a whole list and do something to each element it's a lot cleaner<\/p>\n<pre lang=\"java\" line=\"1\">\r\n\/\/let's serialize all the messages...\r\nList<Message> messages = ...;\r\nUtils.map(messages, new MapFunction<Message> {\r\n   public void map(Message message) {\r\n      Engine.INSTANCE.SERIALIZER.save(message);\r\n   }\r\n});\r\n<\/pre>\n<p>done deal.<\/p>\n<p><strong>Update<\/strong><\/p>\n<p>Here's another Map utility that let's your map() function know about the index of your current element. You may have to treat certain elements differently based on their position in the list.<br \/>\nThis time your function takes a \"IndexMapFunction<T>\" implementation.<\/p>\n<pre lang=\"java\" line=\"1\">\r\npublic static <T> void map(List<T> list, IndexedMapFunction<T> mapFunction) {\r\n\t\tint size = list.size();\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tmapFunction.map(i, list.get(i));\r\n\t\t}\r\n}\r\n<\/pre>\n<p>The interface for IndexedMapFunction looks like this<\/p>\n<pre lang=\"java\" line=\"1\">\r\npublic interface IndexedMapFunction<T> {\r\n\tpublic void map(int i, T obj);\r\n}\r\n<\/pre>\n<p>In your implementation of \"map(int i, T obj)\", \"i\" represents the position of the element being treated. You could do different things depending on what position of the List you are. For example, you could know if you're at the beggining or end of the list, or maybe you could other data structure telling you things about some positions in the list in question.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I read on some email signature something along the lines of: &#8220;If I had a dollar for every for(int i=0; i < size; i++) { ... } I've written I'd be rich\" After coding on Android and learning about some of the tips for performance, like \"With an ArrayList, a hand-written counted loop is about [&hellip;]\n<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[15,30],"tags":[583,1000],"class_list":["post-2047","post","type-post","status-publish","format-standard","hentry","category-code","category-geeklife","tag-java","tag-tips"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p5Unzf-x1","jetpack-related-posts":[{"id":2792,"url":"https:\/\/www.gubatron.com\/blog\/java-have-a-jtables-column-preferred-width-adjusted-to-perfectly-to-the-size-of-the-longest-string-in-the-model\/","url_meta":{"origin":2047,"position":0},"title":"Java: Have a JTable&#8217;s column preferred width adjusted perfectly to the size of the longest string in the model","author":"gubatron","date":"October 30, 2012","format":false,"excerpt":"Here's a utility method I've coded for FrostWire's partial download dialog. With it I'm able to adjust a JTable's column by iterating over the table's column model data and calculating the exact dimensions required to render the longest string found. You can specify a maximum width (to avoid some really\u2026","rel":"","context":"In \"java\"","block_context":{"text":"java","link":"https:\/\/www.gubatron.com\/blog\/tag\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2887,"url":"https:\/\/www.gubatron.com\/blog\/android-changing-textview-alpha-transparency-across-different-target-sdks\/","url_meta":{"origin":2047,"position":1},"title":"Android: Changing TextView alpha transparency across different target SDKs","author":"gubatron","date":"November 30, 2012","format":false,"excerpt":"Sometimes you may need to make a TextView (label) look a little transparent to make emphasis on other parts of your UI. The .setAlpha() function on TextView is not supported after later in the SDK. Here's a static workaround you can place on some sort of UIUtils class you may\u2026","rel":"","context":"In \"Android\"","block_context":{"text":"Android","link":"https:\/\/www.gubatron.com\/blog\/tag\/android\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2142,"url":"https:\/\/www.gubatron.com\/blog\/how-to-convert-android-gps-coordinates-into-xy-coordinates\/","url_meta":{"origin":2047,"position":2},"title":"How to convert Android GPS coordinates into X,Y coordinates.","author":"gubatron","date":"December 30, 2010","format":false,"excerpt":"Without further math bullshit about all the conversion systems, when you have a bunch of Android GPS coordinates (which are compatible with Google Earth and Google Maps), and you want to draw them on a finite 2D plane, here's what worked for me. [java] int x = (int) ((PLANE_WIDTH\/360.0) *\u2026","rel":"","context":"In &quot;Android&quot;","block_context":{"text":"Android","link":"https:\/\/www.gubatron.com\/blog\/category\/android\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2926,"url":"https:\/\/www.gubatron.com\/blog\/how-to-check-if-a-java-process-is-running-on-any-local-virtual-machine-programatically\/","url_meta":{"origin":2047,"position":3},"title":"How to check if a Java Process is running on any local Virtual Machine programmatically","author":"gubatron","date":"January 30, 2013","format":false,"excerpt":"Quick and dirty way to check if a Java Process is already running. Useful if you need to run cronjobs periodically and you don't know how long they might take, you can add this check at the beginning of your main, and it'll look for all the local virtual machines\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1269,"url":"https:\/\/www.gubatron.com\/blog\/how-to-make-a-quick-dirty-hexviewer-updated\/","url_meta":{"origin":2047,"position":4},"title":"How to make a Quick &#038; Dirty HexViewer &#8211; Updated","author":"gubatron","date":"April 20, 2009","format":false,"excerpt":"After I received comments from ispak on Flickr I made a few fixes. ispak pointed out that it was a bad idea reading one byte at the time, also I had a gay ass try\/catch that didn't catch any exception :p So now I read 16 byte chunks, and I\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"HexViewer - r2","src":"https:\/\/i0.wp.com\/farm4.static.flickr.com\/3486\/3458529439_31357e0afe_o.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/farm4.static.flickr.com\/3486\/3458529439_31357e0afe_o.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/farm4.static.flickr.com\/3486\/3458529439_31357e0afe_o.png?resize=525%2C300 1.5x"},"classes":[]},{"id":156,"url":"https:\/\/www.gubatron.com\/blog\/portscanner-only-60-lines-of-code\/","url_meta":{"origin":2047,"position":5},"title":"PortScanner &#8211; Only 60 lines of code","author":"gubatron","date":"May 19, 2005","format":false,"excerpt":"Hi, here's a simple port scanner I wrote today in Java. I needed to see something on my server, perhaps you can find it useful. I would say its pretty fast, you can tweak the number of threads and timeouts to adjust to your server\/connection. I did't do much testing\u2026","rel":"","context":"In &quot;Gubatron&quot;","block_context":{"text":"Gubatron","link":"https:\/\/www.gubatron.com\/blog\/category\/gubatron\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/2047","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/comments?post=2047"}],"version-history":[{"count":3,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/2047\/revisions"}],"predecessor-version":[{"id":2757,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/2047\/revisions\/2757"}],"wp:attachment":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/media?parent=2047"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/categories?post=2047"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/tags?post=2047"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}