前几天面试的时候被面试官出了这样的一道题:
有一个Map为Map<String,Object>,其中的Object类有三种类型:
1.Person类;
2.List<person>或者List<List<person>>或者List<List<List<person>>>等等等等…
3.Map<String,Object>(此Map和题中的Map一样内部有三种类型);
(其中的Person已经指定好,不用自己写)
现将这个Map中包涵的所有的Person类对象都打印出来
面试的时候想到用instanceof和递归解决,但只写出来一半,现在将完整题解写一下
Person类
public class Person{ private String name; public Person(String name) { this.name = name; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + '}'; } }
用于生成包涵三种类型的Map的工具类
public class MapCreate { public static Map<String, Object> map = new HashMap<>(); static { setMap(); } private static void insertList(Map<String, Object> map, String... name) { ArrayList<Person> people = new ArrayList<>(); people.add(new Person(name[0])); people.add(new Person(name[1])); ArrayList<Person> peopleIn = new ArrayList<>(); peopleIn.add(new Person(name[2])); peopleIn.add(new Person(name[3])); ArrayList<Person> peopleIn2 = new ArrayList<>(); peopleIn2.add(new Person(name[4])); peopleIn2.add(new Person(name[5])); ArrayList<List<Person>> listInList = new ArrayList<>(); ArrayList<List<Person>> listInList2 = new ArrayList<>(); listInList.add(peopleIn); listInList2.add(peopleIn2); ArrayList<List<List<Person>>> listInListInList = new ArrayList<>(); listInListInList.add(listInList2); map.put("list", people); map.put("listInList", listInList); map.put("listInListInList", listInListInList); } private static void setMap() { map.put("zhang", new Person("张三")); map.put("li", new Person("李四")); map.put("wang", new Person("王五")); HashMap<String, Object> innerMap = new HashMap<>(); innerMap.put("a", new Person("AAA")); innerMap.put("b", new Person("BBB")); innerMap.put("c", new Person("CCC")); innerMap.put("map", new HashMap<String, Object>()); insertList(innerMap, "mapListPerson1", "mapListPerson2", "mapListInListPerson1", "mapListInListPerson2", "mapListInListInListPerson1", "mapListInListInListPerson2"); map.put("map", innerMap); insertList(map, "listPerson1", "listPerson2", "listInListPerson1", "listInListPerson2", "listInListInListPerson1", "listInListInListPerson2"); } }
利用递归和instanceof实现
public class Main { private static List<Person> personList = new ArrayList<>(); public static void main(String[] args) { searchMap(MapCreate.map); for (Person person : personList) { System.out.println(person); } } private static void searchMap(Map<String,Object> map){ Collection<Object> values = map.values(); for (Object value : values) { if(value instanceof Person){ personList.add((Person) value); }else if(value instanceof Map){ searchMap((Map<String, Object>) value); }else if(value instanceof List){ searchList((List<Object>) value); } } } private static void searchList(List<Object> list){ for (Object o : list) { if(o instanceof Person){ personList.add((Person) o); }else if(o instanceof List){ searchList((List<Object>) o); } } } }