在Java中查找大型数据数组中的特定元素?

huangapple go评论62阅读模式
英文:

Finding specific element in large data Array in Java?

问题

我有一个食物项目的 JSON 数组,数组的大小为 80000,因此我需要从这个大数组中找到特定的元素,并进行一些比较。

比较是通过另一个字符串数组中的元素进行的。

目前我是这样做的:


    try (JsonReader reader = new JsonReader(new FileReader("tessdata/fooditems_col_array.json"))) {
    
        reader.beginArray();
        int i = 0;
        while (reader.hasNext()) {
            String name = reader.nextString();
            System.out.println(name);
            if(name.equalsIgnoreCase("mackeral")){
                i++;
            }
        }
        reader.endArray();
        System.out.println("found" + i);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

有什么更有效率的方法来执行这个操作吗?

提前感谢。

英文:

I have JSON array of food items and size of the array is 80000, so i need to find specific element from the large array, and do some comparison.

Comparison is done with the elements from another array of Strings

for now i'm doing it like following,


    try (JsonReader reader = new JsonReader(new FileReader("tessdata/fooditems_col_array.json"))) {
    
                reader.beginArray();
                int i = 0;
                while (reader.hasNext()) {
                    String name = reader.nextString();
                    System.out.println(name);
                    if(name.equalsIgnoreCase("mackeral")){
                        i++;
                    }
    
                }
                reader.endArray();
                System.out.println("found"+i);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

what is the most efficient way to perform this operation ?

Thanks in advance.

答案1

得分: 1

如果你知道数组是有序的,你可以使用二分查找。如果你知道你需要经常访问它,最高效的方式应该是将其插入到像SQLite、MySQL或MongoDB这样的数据库中,并创建一个索引。如果你只启动程序一次,但要搜索许多条目,哈希映射(HashMap)也可以胜任这个任务。但如果只需在其中搜索一次,没有比线性搜索更好的方式了。

英文:

If you know that the array is sorted, you can do binary search. If you know that you will need to access it more often, the most efficient ways should be to just insert it into a database like SQLite, MySQL or MongoDB and create an index. If you only start the program once, but search for many entries, a HashMap could do the job too. But for searching something in it once, there is no better way than linear search.

huangapple
  • 本文由 发表于 2020年10月23日 01:51:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64487875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定