简体   繁体   中英

Java, how to make this into a generic method?

How would I refactor the code below into 1 generic method?
(background info, it is used to get values from a Json string used with GSON library)

ArrayList<Map<Object, Object>> theme = new ArrayList<Map<Object, Object>>();
for (int i = 0; i < obj.getThemeList().size(); i = i + 1) {
    if(Boolean.parseBoolean(obj.getThemeList().get(i).getChecked())){
        Map<Object,Object> map = new HashMap<Object,Object>();
        map.put("id", obj.getThemeList().get(i).getId());
        map.put("name", obj.getThemeList().get(i).getName());
        theme.add(map);
    }
}

ArrayList<Map<Object, Object>> tag = new ArrayList<Map<Object, Object>>();
for (int i = 0; i < obj.getTagList().size(); i = i + 1) {
    if(Boolean.parseBoolean(obj.getTagList().get(i).getChecked())){
        Map<Object,Object> map = new HashMap<Object,Object>();
        map.put("id", obj.getTagList().get(i).getId());
        map.put("name", obj.getTagList().get(i).getName());
        tag.add(map);
    }
}

Basically, just make it a single method that accepts the getThemeList() or getTagList() , no? It looks like that's the only difference between them...

I think you mean "how can I refactor this to reuse code", because generics does not apply here as much as refactoring does.

Firstly, read up on the foreach syntax - your for loop is really ugly.

You haven't given much to go on, but try this:

public interface HasIdNameAndChecked {
    String getChecked();
    String getId();
    String getName();
}

public static List<Map<String, String>> extractList(List<? extends HasIdNameAndChecked> items) {
    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    for (HasIdNameAndChecked item : items) {
        if (Boolean.parseBoolean(item.getChecked())){
            Map<String, String> map = new HashMap<String, String>();
            map.put("id", item.getId());
            map.put("name", item.getName());
            list.add(map);
        }
    }
    return list;
}

Then have your Theme and Tag classes implement HasIdNameAndChecked , and call it like this:

List<Map<String, String>> list1 = extractThemeList(obj.getThemeList());
List<Map<String, String>> list2 = extractThemeList(obj.getTagList());

Disclaimer: I typed this in without an IDE, so there could be a couple of typos.

Well, let's do it in following order:

  1. Identify what varies. themeList and tagList.

  2. Identify common properties and behaviour. getChecked(), getId(), getName().

  3. Apply generalization for what varies. Define a common interface for what varies: abstract class, interface, behaviour, etc.

  4. Update your solution to generalized solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM