简体   繁体   中英

Recursive search for values in a list of Hashmaps with java

I'm trying to loop through a list of hashmaps and form a tree like structure.The input(list of hashmaps) and the desired output(list of hashmaps) are as below:

input:

[{State=Tamil Nadu, Continent=Asia, Country=India, City=Chennai}, {State=Kerala, Continent=Asia, Country=India, City=Cochin}, {State=Tamil Nadu, Continent=Asia, Country=India, City=Madurai}, {State=Something, Continent=Asia, Country=Srilanka, City=Colombo}, {State=anythig, Continent=Africa, Country=South Africa, City=new}]

Expected Result:

[{children=[{children=[{State=Tamilnadu, children=[{City=Madurai}, {City=Chennai}]}, {State=Kerala, children=[{City=Cochin}]}], Country=India}, {Country=Srilanka}], Continent=Asia}, {Continent=Africa}]

(Please consider that even Srilanka and Africa should have the same structure. I havent added that since its a sample)

The main aim is to form a tree like structure like below:

  Asia
    India
      TamilNadu
        Chennai
        Madurai
      Kerala
        Cochin
    Srilanka
      Something
        Colombo
  Africa
    South Africa
      Anything
        new

All data would be dynamic and the only given input would be the group order which is like "Continent, Country, State, City" meaning that city comes under State and state comes under country and so on. What I had tried in the below code is to search through the input list, first get the city, form a map of the city then find the index list in which the map contains the value of each city and get the state, add them in a map and add the corresponding city under the state which the key children (I thought of doing it in a recursive way but not able to get an idea)which is important as the final list of maps will be converted to a json input for a tree store. This has to be done in the java code and im struck with it. Could anyone provide a sample or any pointers...

public void recursiveSearch(List<Map<String, String>> inputList){
    String groupOrder = "Continent, Country, State, City";
    String[] splitList = groupOrder.split(",");
    Map finalMap = new HashMap();
    for(int i= splitList.length-1; i >= 0; i--){
        //int index = 0;
        List searchList = new ArrayList();
        String keyToSearch= splitList[i].trim();
        for (Map<String, String> map : inputList) {

        String searchVal= map.get(keyToSearch);
        //index =  inputList.indexOf(map);
        //System.out.println(index);
        if(!searchList.contains(searchVal)){
            searchList.add(searchVal);
        }
        //System.out.println(searchVal);
    }
    if(searchList.size() > 0){
        Map allSearchMap = new HashMap();
        Map indSearchMap= new HashMap();
        for(int j=0; j < searchList.size(); j++ ){
            int index = 0;
            //System.out.println(splitList[splitList.length-1] +" "+ keyToSearch);
            if(((splitList[splitList.length-1]).trim()).equalsIgnoreCase(keyToSearch)){

              Map indexMap = new HashMap();
              for (Map<String, String> newMap : inputList) {

                    boolean result= newMap.containsValue(searchList.get(j));
                    if(result){
                        index =  inputList.indexOf(newMap);
                        System.out.println(searchList.get(j)+ " "+index);
                    }


                }
              indexMap.putAll(inputList.get(index));
              if(indexMap != null){
                  if(!indSearchMap.containsValue(searchList.get(j))){
                  indSearchMap.put(keyToSearch, searchList.get(j));
                  }
                  allSearchMap.put(keyToSearch+j, indSearchMap);
                  if(i-1 >= 0){
                  String parent = (String) indexMap.get(splitList[i-1].trim());

                  finalMap.put(splitList[i-1].trim(), parent);
                  finalMap.put("children", allSearchMap.get(keyToSearch+j));
                  //System.out.println(index+ " "+searchList.get(j)+" "+indexMap.get(splitList[i-1].trim()));
                  }
              }

            }



    }
}
}
System.out.println("--->"+finalMap.toString());

}

NOTE: The data and the group order are dynamic and can be of anything or any count.

Try this

public class MyObjectClass implements Comparable<MyObjectClass> {

private String continent;
private String country;
private String state;
private String city;

public MyObjectClass(String continent) {
    this.continent = continent;
}

public String getContinent() {
    return continent;
}

public void setContinent(String continent) {
    this.continent = continent;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

@Override
public int compareTo(MyObjectClass o) {
    if (this.continent.compareTo(o.continent) > 0)
        return 1;
    else if (this.continent.compareTo(o.continent) < 0)
        return -1;
    else
        return 0;

}
}

Then My main class. This will return your expected out put.

import java.util.*;

public class MyMain {
public static void main(String[] args) {

    List<MyObjectClass> list=new ArrayList<>();
    MyObjectClass myObj1=new MyObjectClass("Asia");
    myObj1.setCountry("Sri Lanka");
    myObj1.setState("Western");
    myObj1.setCity("Colombo");

    MyObjectClass myObj2=new MyObjectClass("Africa");
    myObj2.setCountry("South Africa");
    myObj2.setState("Anything");
    myObj2.setCity("new");

    MyObjectClass myObj3=new MyObjectClass("Asia");
    myObj3.setCountry("India");
    myObj3.setState("Tamil Nadu");
    myObj3.setCity("Chennai");

    MyObjectClass myObj4=new MyObjectClass("Asia");
    myObj4.setCountry("India");
    myObj4.setState("Kerala");
    myObj4.setCity("Cochin");

    list.add(myObj1);
    list.add(myObj2);
    list.add(myObj3);
    list.add(myObj4);

    Collections.sort(list);
    String tempCont=new String();
    String tempCount=new String();
    String tempState=new String();
    for(MyObjectClass i:list){
        if(tempCont.equals(i.getContinent())){
            if(tempCount.equals(i.getCountry())){
                if (tempState.equals(i.getState())){
                    System.out.println("-------------------------"+i.getCity());
                }
                else {
                    tempState=i.getState();
                    System.out.println("----------------"+tempState);
                    System.out.println("-------------------------"+i.getCity());
                }

            }
            else {
                tempCount=i.getCountry();
                System.out.println("--------"+tempCount);
                System.out.println("----------------"+i.getState());
                System.out.println("-------------------------"+i.getCity());
            }
        }
        else {
            tempCont=i.getContinent();
            System.out.println(tempCont);
            System.out.println("--------"+i.getCountry());
            System.out.println("----------------"+i.getState());
            System.out.println("-------------------------"+i.getCity());
        }

    }
}
 }

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