简体   繁体   English

通过字符串搜索数组列表

[英]Searching Array List by a String

One problem that I am facing in my code is that I have a long list of strings that map to different integers. 我在代码中面临的一个问题是,我有一长串的字符串映射到不同的整数。 For example, "Apple" maps to 4, "Bat" maps to 7, etc. Is there any ways to create an Array List such that a string is used as the input search element rather than a traditional number? 例如,“ Apple”映射到4,“ Bat”映射到7,依此类推。是否有任何方法可以创建一个数组列表,以便将字符串用作输入搜索元素而不是传统数字? Ie. IE浏览器。 Array["Apple"] instead of Array[4] Array [“ Apple”]而不是Array [4]

ArrayList doesn't have that support. ArrayList没有该支持。 But Hashmaps can solve your usecase. 但是Hashmap可以解决您的用例。 Check that out. 检查出。

Use an associative data structure for this. 为此,请使用关联数据结构。

Map<String, Integer> items = new HashMap<>();
items.put("Apple", 4);
items.put("Bat", 7);

items.get("Apple");
items.get("Bat");

You can use a Map to solve your use case. 您可以使用Map来解决您的用例。

Map<String, Integer> fruits = new HashMap<String, Integer>();

Now your fruits Map will have the String as a key and Integer as a value. 现在,您的水果地图将把String作为键,将Integer作为值。

To put key-value: fruits.put("Apple", 1) 放置键值: fruits.put("Apple", 1)
To get value based on key: fruits.get("Apple") 根据密钥获得价值: fruits.get("Apple")

You will need two data structures for this problem: a Map to associate item names with indices and a List to store the items (eg an ArrayList ). 您将需要两个数据结构来解决此问题:将项目名称与索引相关联的Map和用于存储项目的List (例如ArrayList )。 For example (untested): 例如(未测试):

// Store the items and a mapping of their indices by name.
List<String> items = new ArrayList<String>();
Map<String, Integer> itemIndices = new HashMap<String, Integer>();
// Add the item to both data structures.
itemIndices.put("Apple", 4);
items.add("Apple", 4);
// Now you can fetch them by name.
items.get(itemIndices.get("Apple")); // => "Apple"

Of course, you can use a Map<String,Integer> directly, with no need for the List ... 当然,您可以直接使用Map<String,Integer> ,而不需要List ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM