优化哈希图中的搜索时间



我有一个经过哈希映射的csv文件,每当用户输入城市名称(键(时,它都会显示该城市的所有详细信息。我必须优化搜索结果时间,每次它读取文件(而不是只有一次(并显示值。CSV文件包含如下数据:

城市,city_ascii,纬度,液化天然气,国家,ISO2,ISO3,admin_name,首都,人口,ID Malishevë,Malisheve,42.4822,20.7458,科索沃,XK,XKS,Malishevë,admin,,1901597212 普里兹伦,普里兹伦,42.2139,20.7397,科索沃,XK,XKS,普里兹伦,admin,,1901360309 祖宾波托克,祖宾波托克,42.9144,20.6897,科索沃,XK,XKS,祖宾 波托克,管理员,1901608808

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.IOException;
public class CSVFileReaders{
public static void main(String[] args) {
    String filePath = "C:\worldcities1.csv";
    Scanner in = new Scanner(System.in);                                      
    System.out.println(" n Enter the City name to be Searched :   n _> ");
    long start = System.currentTimeMillis();
    String searchTerm = in.nextLine();
    readAndFindRecordFromCSV(filePath, searchTerm);
    long end = System.currentTimeMillis(); 
    System.out.println(" n It took " + (end - start) + " Milli Seconds to search the result n");
    in.close();
}
public static void readAndFindRecordFromCSV( String filePath, String searchTerm) {
    try{            
        HashMap<String,ArrayList<String>> cityMap = new HashMap<String,ArrayList<String>>();        
        Scanner x = new Scanner (new File(filePath),"UTF-8");
        String city= "";
        while(x.hasNextLine()) {
        ArrayList<String> values = new ArrayList<String>();
        String name  = x.nextLine();
        //break each line of the csv file to its elements
        String[] line = name.split(",");
        city = line[1];
            for(int i=0;i<line.length;i++){
                values.add(line[i]);            
            }
        cityMap.put(city,values);       
        }
        x.close();
        //Search the city
        if(cityMap.containsKey(searchTerm)) {
                System.out.println("City name is : "+searchTerm+"nCity details are accordingly in the order :"
                                    + "n[city , city_ascii , lat , lng , country , iso2 , iso3 , admin_name , capital , population , id] n"
                                    +cityMap.get(searchTerm)+"");
            }           
        else {
            System.out.println("Enter the correct City name");
        }                       
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}'

时间应该优化,每次我搜索它都会读取整个文件(应该发生(

目前,您将地图初始化混合在搜索功能中。
你不想要那个。
首先,初始化地图,然后在搜索功能中使用它。
为此,请为实例化和评估映射的语句提取一个方法,然后重构readAndFindRecordFromCSV()方法,以便它接受Map作为附加参数:

 public static void readAndFindRecordFromCSV( String filePath, String searchTerm,  HashMap<String,ArrayList<String>> dataByCity) {...}

通过重构IDE功能,它应该足够简单:"提取方法",然后"更改签名"。

这是一个代码(未在运行时测试,但在编译时测试(,它将逻辑拆分为单独的任务,并且还依赖于实例方法:

public class CSVFileReaders {
    private final String csvFile;
    private HashMap<String, ArrayList<String>> cityMap;
    private final Scanner in = new Scanner(System.in);
    public static void main(String[] args) {
        String filePath = "C:\worldcities1.csv";
        CSVFileReaders csvFileReaders = new CSVFileReaders(filePath);
        csvFileReaders.createCitiesMap();
        csvFileReaders.processUserFindRequest(); // First search
        csvFileReaders.processUserFindRequest(); // Second search
    }

    public CSVFileReaders(String csvFile) {
        this.csvFile = csvFile;
    }
    public void createCitiesMap() {
        cityMap = new HashMap<>();
        try (Scanner x = new Scanner(new File(csvFile), "UTF-8")) {
            String city = "";
            while (x.hasNextLine()) {
                ArrayList<String> values = new ArrayList<String>();
                String name = x.nextLine();
                //break each line of the csv file to its elements
                String[] line = name.split(",");
                city = line[1];
                for (int i = 0; i < line.length; i++) {
                    values.add(line[i]);
                }
                cityMap.put(city, values);
            }
            x.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public void processUserFindRequest() {
        System.out.println(" n Enter the City name to be Searched :   n _> ");
        long start = System.currentTimeMillis();
        String searchTerm = in.nextLine();
        long end = System.currentTimeMillis();
        System.out.println(" n It took " + (end - start) + " Milli Seconds to search the result n");
        //Search the city
        if (cityMap.containsKey(searchTerm)) {
            System.out.println("City name is : " + searchTerm + "nCity details are accordingly in the order :"
                                       + "n[city , city_ascii , lat , lng , country , iso2 , iso3 , admin_name , capital , population , id] n"
                                       + cityMap.get(searchTerm) + "");
        } else {
            System.out.println("Enter the correct City name");
        }
    }
}

有趣的部分在这里:

String filePath = "C:\worldcities1.csv";
CSVFileReaders csvFileReaders = new CSVFileReaders(filePath);
csvFileReaders.createCitiesMap();
csvFileReaders.processUserFindRequest(); // First search
csvFileReaders.processUserFindRequest(); // Second search

逻辑现在更清楚了。

为什么每次搜索都要创建/加载CSV到HashMap中?只需在开始时只创建一次 HashMap,然后在每次搜索时只需检查它是否存在于 HashMap 中,例如将读取部分移动到单独的方法中:

HashMap<String,ArrayList<String>> cityMap = new HashMap<String,ArrayList<String>>(); 
public static void readCSVIntoHashMap( String filePath) {
    try{            
        Scanner x = new Scanner (new File(filePath),"UTF-8");
        String city= "";
        while(x.hasNextLine()) {
        ArrayList<String> values = new ArrayList<String>();
        String name  = x.nextLine();
        //break each line of the csv file to its elements
        String[] line = name.split(",");
        city = line[1];
            for(int i=0;i<line.length;i++){
                values.add(line[i]);            
            }
        cityMap.put(city,values);       
        }
        x.close();
    ...
    }

然后有一个单独的搜索方法:

public static void search(String searchTerm) {
  if(cityMap.containsKey(searchTerm)) {
  ...
}
}

最新更新