How to iterate over a Collection in Java?

Traditional way

List<Integer> numbers = ...

for (int i = 0; i < numbers.length(); i++) {
    if (i % 2 == 0) {
        Integer value = numbers.get(i);
        if (value % 2 == 0) {
            // do something to value

– an iconic way
– can access to both index and value at the same time

– too much code

– when you need to know the index of the element in a loop.

The Iterator way

In Java, Array and Collection all implement Iterable which returns an Iterator.

List<Integer> numbers = ...

for (Iterator<Integer> it = numbers.iterator(); it.hasNext();) {
    Integer value =;
    if (value % 2 == 0) {

If you need to know the index, use ListIterator (only work with List):

List<Integer> numbers = ...

for (ListIterator<Integer> it = numbers.listIterator(); it.hasNext();) {
    Integer index = it.nextIndex();
    Integer value =;
    if (index % 2 == 0 && value % 2 == 0) {

– supports iterator over all kinds of Collection types (Set, Queue, etc)
– can remove elements during iteration.
– faster than Tranditional way in case of LinkedList or other Collection implementation where random access is time-consuming.

– too much code

The Enhanced for way

This is the most recommended way since Java 5 if you just need to iterate over a Collection without the need to access to the index.

List<Integer> numbers = ...

// read as "for each number in numbers"
for (Integer number : numbers) {
    if (number % 2 == 0) {
        // do something with number


To iterate over an entire java.util.Map, please use this:

Map<String, Object> cache = ...

for (Map.Entry<String, Object> entry : cache.entrySet()) {
    doSomeThingTo(entry.getKey(), entry.getValue());

– simple, easy to read
– keep variables’ scopes clean (especially in nested loops)

– cannot access to the index of the element (well, not every time we need it actually)

The Java 8 way (or the function way or the lambda way)

In Java 8, Stream API has been introduce which makes it very easy to iterate and do somthing no elements of a Collection.

List<Integer> numbers = ...
    .filter(number -> numbers % 2 == 0)
        .forEach(number -> doSomething(number));

// or simply

numbers.forEach(number -> doSomething(number));

– easy to write and read
– method chain
– lazy evaluate

– the API has quite a lot of methods so it takes time to master all of them.


My girlfriend shared me an interesting video tonight. It recorded a situation happened in a hospital in which the nurse and the doctor were trying to save a new born baby. The little one seemed to stop breathing. What moved me was how persistent the nurse and the doctor were to save the baby. The nurse, an old lady, tried to warm up the baby’s body by putting on oil, then slapped him in order to make him cry. The doctor did CPR and also helped the nurse to warm him up. But the baby, despite the effort, did not move an inch. They kept doing. After round 10 minutes, the baby moved a little bit and he opened his eyes. They did it. They had successfully saved the baby, bring him back to life. What a relief!

I could image how happy the mother was when she heard the news about her baby being saved. The nurse and the doctor could have gone home, go to bed, and be proud that they did something big that night. They saved a baby, they saved a family. If it were me, I would have had a very good sleep with a smile in my face.

There were lots of things I learned through the video, but one thing made me want to write it out. At some point in the video, there had been a close look at the nurse. A kind old lady. She could have been a grandma to some kids. However, look at how agile she was in handling the situation. Every move she made was precise and with care. The new born baby looked very small and fragile, like a doll. The old nurse moved the baby very quickly, genlty carrying him up and down and then slapped him to wake him up. All of her focus at that moment was how to protect but save the baby. It looked like she had gone through this situation a lot and that was not her first time doing this.

The nurse could have been working in the hospital for decades. She didn’t become a doctor. She didn’t the move out to another hospital for a raise, I guess. She was there to serve and to save people.

I realized that it was stupid and ignorance if I compare the nurse’s job with the other higher paid jobs like CEO or Chairman. I could see that The Nurse loved what she did. She could have been saved lots of life. What she did gradually changed the world. It was how she did it that mattered the most. Every job has its own differences.

It made me question myself. How had I been doing? Had I put in enough passion in every action I made? Stop comparing your job to others.

Big Data and its application?

I & my girlfriend was coming back to our hometown, Bien Hoa city. As usual, every time I was in motion, I always have some really deep thought.

When she & I was discussing about how we could invest money by buying gold and then selling again to make some profit, a thought came to me that we can develop a algorithm that can analyze the up & down of gold market and predict when should buy and when we should sell gold to make the best profit. And this can apply to every thing, for example, real estate, clothing, stock, etc. Or we can gather data from Google Map and then apply principle of Feng Shui to detect and suggest which land we can invest and make profit.

The problem is, how can I develop such system when I don’t have any knowledge and experience in Data Analysis and Big Data algorithm. I think I need to consult with someone else about this.

Knowing Your Code’s Structure

I haven’t paid much attention to how the classes in my projects communicate with each other. Looking at the package structure, they all look good and well-organized. Then one day, I came across the article Your Code Structure and it made me to seriously think about re-validate my source code.

In the article, Edmund Kirwan used his tool, named Spoiklin Soice, to analyze the modules of JUnit from the early version to the latest one. The result was that as JUnit evolving, its classes had become more tangled and its structure had become a real mess (according to the graph).

This was really interesting because JUnit had been a widely known & used by almost all Java developers and it was developed by the lengedary Kent Beck. In the article, the latest version of JUnit, 4.11, had become really complex due to new features added into the library. I had always thought of JUnit as a powerful and well-tested tool and never paid attention to its structure and design ever since I used it. It could be the case that as time goes by, JUnit would become more and more difficult to extend and mantain due to its complexity.

Well, that was for JUnit, how about my projects? Spoiklin Soice is really interesting tool, I will use it to analyze them to see whether the structure is still controllable.

But what if we knew that the structure of a project had become too complex, what we could do to make it right again? Or there are any principle that we could follow and then keep everything in its right position?

Download and read more about Edmund’s work at his blog:

Prepare to Getting Real

I’m bored tonight. So I go to my bookmark bar to see whether there is something I can read. Bingo! I came across the @freebook folder and click on Getting Real. This is a free version of 37signal’s book, Getting Real where it talk about how to quickly and efficiently start up a new software product which solve the problem from the begining. Start small, focus and efficient. I will continue to read it tomorrow.

Here is the link to the free book:

Agile toolkits

My current company is using Scrum to develop softwares. To me, it is a set of practices and tools which enhances communication, collaboration, trusts, etc between members of a team.
What people are still debating is that, which one, Scrum or Lean is better. I said, why not both? To me, the term Agile has been broaderned to bear many meanings. It points to a lot of processes. But under the hood. It is still 4 statements and 12 principles of Agile Manifesto. Everything else is just a technique. We can decompose Scrum or Lean into techniques and combines several ones to form a new method. To see if it works, we have to try it. But in the end, they are just tools.

Why there is no SoftHashMap?

The above question bumped into me when I was developing a simple cache using java.util.Map. In the search for the answer, I came across a thread on JavaRanch that had the same question as mine. And there was an answer which had widen my knowledge in soft/weark references in Java.

I quoted the answer here in case the link is inaccessible.

In the few cases, where I used weak references (or soft references), I used the classes, (and queues) directly. Never used the WeakHashMap class. So, never thought about the possibility of the SoftHashMap class. IMO, the WeakHashMap class was written for internal (as support) reasons, and then exposed because others may need it. Maybe that is why SoftHashMap was never written.

In thinking about it a bit more, I don’t think that it is possible to write a SoftHashMap class. Remember that a SoftHashMap isn’t just a WeakHashMap that is using SoftReferences. It has to also not “distrurb” those soft references. Let me explain….

To implement a WeakHashMap, just use WeakReferences on the keys. This means, of course, that you need to do an additional deference to add/remove the key/value pairs. You will also need to attach a ReferenceQueue so that you can detect that a key has been GC’ed — which the WeakHashMap will use to automatically delete the key-value pair.

There is a minor flaw though — particularly if more than one key lands in a bucket. The WeakHashMap needs to deference the key (ie. make it a hard reference temporarily) so that it can use the hashCode() and equals() methods for the operation. This means, that in theory, it is possible for a key (that isn’t referenced by the application) to survive a GC cycle — if by chance theWeakHashMap is doing this operation….. This is probably not a big deal, as the chances are ridiculously low, and it can be picked up on the next GC cycle.

This becomes a major flaw with the SoftHashMap. Remember that SoftReference objects may or may not be GC’ed even if there are no hard references. It is at the whim of the JVM, which decides based on the amount of memory that it needs. The idea is, if there are lots of memory being freed, there is no reason to completely delete a cache that could be useful to the application.

The issue is, the SoftReference determines which instance to GC based on the access — it keeps timestamps of which object has been used and how recent (Least Recently Used). This means, that the temporary conversion of the soft reference to a hard reference (to do the equals()) will affect the LRU. A key that hasn’t been accessed by the application in a very long time, may survive a GC purely because it shares a bucket with a more commonly used key. And unlike the WeakHashMap issue, the chances are not low, and it may not be picked up in the next GC cycle.

Basically, you have a SoftHashMap that has soft references, but isn’t really a soft hash map.

Henry Wong

The link:

My father is a …

My father is a writer. A good one. His name is Marc Norman.

He wrote Shakespeare In Love and a hundred other scripts and novels and has two oscars on his mantle.

He told me this about writing…

It’s a full time job. To be successful you must be disciplined. You do it from nine to five, five days a week. Focus on your work for forty hours and put it away at night and on the weekends. When you’re blocked write something else, sonnets, poems, the “other novel”, love letters. The point is you must write full-time. A writer’s talent is a muscle that must be worked out, and like a bicep it will strengthen with use.

Writers write alone, in quiet. Writers don’t write in coffee-shops. Silence is the blank canvas onto which the world of the work is drawn.

I found this on an anwers on Quora:

SQL isn’t dead. JooQ is a new fresh thing

After working with 3 layers, DAO, JPA and Hibernate and stuff, I think writing native SQL code is going to disappear. However, til today, I just found a new framework that support you to write SQL command by Java code. Their fluent API is so good that it seems identical with real SQL command.

Check out JOOQ – Java Object Oriented Querying;

P.s: Guess what! It’s type-safe.

Little things matter

Today, I’ve read a entry in Quora that actually Made Me Thing (MMT). It was a survey “What is the nicest thing anyone has ever done to you?” and there was a man writing that some woman had helped him back when he was travelling in Swizertland and making his way to his home in Rome. The woman had spent over 2 hours to sit with him, hopping trains in order to make sure he made it way home safe. He had been moved by the action and really appreciated the woman’s action. He even stated that to him the most nicest country is Swizertland.

After reading the post, I just realized that doing a little thing with your heart really matters. You don’t need to do big things to impress people. Doing a little thing with your heart in it and specially with careness is actually the most thing that help you “win” people.

So, how about my closet person? My girlfriend? My mother? My sister? My colleagues? What litte things I can do for them to make them feel better NOW?