How to remove duplication from my code

java, refactoring

Solution

A generic Interface Action that have a method action(T t) can reduce the code.

public interface Action<E> {
        void action(E e);
}

Example:

public static void forEach(List<String> list, Action <String> action) {
    for(String s : list){
           action.action(s);

}

Now you just need 2 different implementations of Action.

You can use annonymous types if you don't want to create a class.

If you know c# this is similar to lambdas.

edit:

Using annonymous type:

public static Map<String, String> getSomething(List<String> list) {
    final Map<String, String> map = new HashMap<String, String>();
    forEach(list, new Action<String>() {
        @Override
        public void action(String e) {
            if (e.contains("aaa")) {
                map.put("aaa", e);
            }
            if (e.contains("bbb")) {
                map.put("bbb", e);
            } else {
                // do nothing
            }
        }
    });
    return map;
}

Creating the class:

public static Map<String, String> getSomething2(List<String> list) {
    final Map<String, String> map = new HashMap<String, String>();
    forEach(list, new ListToMapAction(map));
    return map;
}


public class ListToMapAction implements Action<String> {

    Map<String, String> map;

    public ListToMapAction(Map<String, String> map) {
        this.map = map;
    }

    @Override
    public void action(String e) {
        if (e.contains("aaa")) {
            map.put("aaa", e);
        }
        if (e.contains("bbb")) {
            map.put("bbb", e);
        } else {
            // do nothing
        }
    }

}

Problem

I have two similar methods. One of them prints something and one of them save somethings. As you can see there are a lot of duplicate code. How should I refactor it and remove this duplication ? ``` public static void printSomething(List<String> list) { for (String item : list) { if (item.contains("aaa")) { System.out.println("aaa" + item); } if (item.contains("bbb")) { System.out.println("bbb" + item); } else { System.out.println(item); } } } public static Map<String, String> getSomething(List<String> list) { Map<String, String> map = new HashMap<String, String>(); for (String item : list) { if (item.contains("aaa")) { map.put("aaa", item); } if (item.contains("bbb")) { map.put("bbb", item); } else { //do nothing } } return map; } ``` UPDATE: Code was updated to solve problem when method are not exactly similar

Original source