Q:

processing list of objects in Java

I have a list of objects and i want to process subset of objects based on condition and then create a new list with processed objects.
The List if Objects
miss | shannon sperling
mr | john smith
prof | kim taylor
prof.dr | kim taylor

In the above list i want to the names which has two titles(kim taylor) and glue the title because prof is a subset of prof.dr. My final list should look like the following
miss | shannon sperling
mr | john smith
prof.dr | kim taylor  

I tried with following code
void gluetitles(List title)
       {
           for (int i=0;i<title.size();i++) { 
                String names = (String) title.get(i);
                String[] titlename=names.split("\\|");\\split the list with delimiter and extracts titles and names
                String tle=titlename[0];
                String name=titlename[1];

           }     
       }

But i did not get idea how to compare and get the name which has two titles.

A:

This code works fine...
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Notepad {

    public static void main(String args[]) {
        final List<String> titles = new ArrayList<>();
        titles.add("miss | shannon sperling");
        titles.add("mr | john smith");
        titles.add("prof | kim taylor");
        titles.add("prof.dr | kim taylor");
        gluetitles(titles);
    }

    static void gluetitles(final List<String> titles) {
        final Map<String, String> titleMap = new HashMap<>();
        for (final String names : titles) {
            final String[] titleName = names.split("\\|");
            final String title = titleName[0];
            final String name = titleName[1];
            if (doesMapContainName(titleMap, title, name)) {
                titleMap.put(name, title);
            }
        }
        for (final Entry<String, String> s : titleMap.entrySet()) {
            System.out.println("Name is " + s.getKey() + " Title is "
                    + s.getValue());
        }
    }

    private static boolean doesMapContainName(
            final Map<String, String> titleMap, final String title,
            final String name) {
        return (titleMap.get(name) != null && titleMap.get(name).length() < title
                .length()) || !titleMap.containsKey(name);
    }
}

The contain method is a bit dirty but the long and short of it is if it exists in the map, check if this new value is longer than the one we already know about, if it is, add it, if it doesn't exist in the map, add it.  This assumes the data always just concatenates the titles like in the example, we have one with prof.dr and one with prof.

