优化哈希图中的搜索时间

时间:2019-02-05 08:57:59

标签: java csv hashmap

我有一个被混编的csv文件,每当用户输入城市名称(密钥)时,它将显示该城市的所有详细信息。我必须优化搜索结果的时间,每次它正在读取文件(而不是一次)并显示值时。 CSV文件包含以下数据:

  

city,city_ascii,lat,lng,country,iso2,iso3,admin_name,capital,population,id   Malishevë,Malisheve,42.4822,20.7458,Kosovo,XK,XKS,Malishevë,admin ,, 1901597212   普里兹伦,Prizren,42.2139,20.7397,科索沃,XK,XKS,普里兹伦,admin,1901360309   Zubin Potok,Zubin Potok,42.9144,20.6897,科索沃,XK,XKS,Zubin   Potok,admin,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();
    }
}

}`

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

2 个答案:

答案 0 :(得分:3)

当前,您在搜索功能中混合了地图初始化。
你不要那个
首先,初始化地图,然后在搜索功能中使用它。
为此,请为实例化并为映射赋值的语句提取一个方法,然后重构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

现在逻辑更清楚了。

答案 1 :(得分:0)

为什么每次搜索都将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)) {
  ...
}
}