Reputation: 687
I have a REST API and I want to call a method which creates the TreeMap from a csv file and I want to use the TreeMap for rest of the each API calls.So I just want to call the method to set the TreeMap and want to use the TreeMap for rest of the API calls.
My method for creating the TreeMap is
public void createTreeMap(){
CSVReader reader = new CSVReader(new FileReader("C:\\Users\\result.csv"), ',' , '"' , 1);
TreeMap <Integer,ArrayList<Long>> result=new TreeMap <Integer,ArrayList<Long>>();
//Read CSV line by line and use the string array as you want
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
//Verifying the read data here
ArrayList<Long> result_01 = new ArrayList<Long>();
for(int k=0;k<nextLine[1].replace("[", "").replace("]", "").replace(" ", "").split(",").length;k++){
result_01.add(Long.parseLong(nextLine[1].replace("[", "").replace("]", "").replace(" ", "").split(",")[k]));
}
result.put(Integer.parseInt(nextLine[0]), result_01);
}
}
}
So below is Rest api Controller
@RestController
public class HomeController {
@RequestMapping(value="/api/sid",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.GET)
public ResponseEntity<Map<String, List<Model>>> getid(@RequestParam("sid") int sid) {
Map<String, List<Model>> Map = new HashMap<String, Object>();
List<Model> model=new List<Model>();
model=get_model();
Map.put("hi",model)
return new ResponseEntity<Map<String, List<Model>>>(Map,HttpStatus.OK);
}
@ResponseBody
public List<Model> get_model(){
List list =new List<Model>();
//here I have to use the treemap
return list;
}
}
I can create the tree map each time when the api is called.but instead of that I need to create it only once and access that in the response body get_model method.Any help is appreciated.
Upvotes: 0
Views: 371
Reputation: 3673
Use singleton bean i.e create another bean to create the TreeMap from csv file and the TreeMap in member variable of bean.
@Bean
public class RefData{
public TreeMap<Object> treeMap;
public TreeMap<Object> getData(){
if(this.treeMap == null){
//read csv file & prepare TreeMap & store it in this.treeMap
}
return this.treeMap;
}
}
Upvotes: 1