如何在不迭代的情况下从散列表中获取一个条目

如果键未知,是否有一种优雅的方法可以从 HashMap 中只获得一个 Entry<K,V>,而不需要迭代。

由于入境顺序并不重要,我们可以这样说吗

hashMapObject.get(zeroth_index);

尽管我知道不存在这样的 get by index 方法。

如果我尝试下面提到的方法,它仍然需要获取散列表的所有条目集

for(Map.Entry<String, String> entry : MapObj.entrySet()) {
return entry;
}

欢迎提出建议。

编辑: 请建议任何其他数据结构,以满足要求。

306025 次浏览

映射不是有序的,所以没有“第一个条目”这样的东西,这也是为什么在 Map(或 HashMap)上没有 get-by-index 方法的原因。

你可以这样做:

Map<String, String> map = ...;  // wherever you get this from


// Get the first entry that the iterator returns
Map.Entry<String, String> entry = map.entrySet().iterator().next();

(注意: 检查省略的空映射)。

您的代码不会获得 map 中的所有条目,它会立即返回(并打破循环)找到的第一个条目。

打印第一个元素的键和值:

System.out.println("Key: "+entry.getKey()+", Value: "+entry.getValue());

注意: 调用 iterator()并不意味着要遍历整个映射。

我想迭代器可能是最简单的解决方案。

return hashMapObject.entrySet().iterator().next();

另一种解决方案(不太好) :

return new ArrayList(hashMapObject.entrySet()).get(0);

或者(也不是更好) :

return hashMapObject.entrySet().toArray()[0];

你说“没有迭代”是什么意思?

您可以使用 map.entrySet().iterator().next(),并且不会迭代 map (在“接触每个对象”的意思中)。但是,如果不使用迭代器,就无法获得 Entry<K, V>地图,入口的 Javadoc 表示:

EntrySet 方法返回一个 地图的集合-视图,其 元素都属于这个类 获得地图参考资料的方法 条目来自这个 这些映射条目 对象只对 迭代的持续时间。

你能更详细地解释一下,你想要完成什么吗?如果您希望首先处理对象,它匹配特定的条件(比如“ have a special key”) ,然后返回到其余的对象,那么请查看 优先队列。它将根据您提供的自然顺序或定制定义的 Comparator对您的对象进行排序。

为什么要避免调用 entrySet()呢? 因为 没有通常会创建一个带有自己上下文的全新对象,而只是提供一个 facade 对象。简单地说,entrySet()是一个相当便宜的操作。

Jesper 给出的答案是好的,另一个解决方案是使用 TreeMap (您要求使用其他数据结构)。

TreeMap<String, String> myMap = new TreeMap<String, String>();
String first = myMap.firstEntry().getValue();
String firstOther = myMap.get(myMap.firstKey());

TreeMap 有一个开销,所以 HashMap 更快,但这只是一个替代解决方案的例子。

根据您的编辑,以下是我的建议:

如果只有一个条目,则可以用双对象替换 Map。 根据不同的类型和你的喜好:

  • 一个数组(由两个值、键和值组成)
  • 具有两个属性的简单对象

这将得到一个单一的条目从地图,这大约是一个人可以得到的,因为“第一”并不真正适用。

import java.util.*;


public class Friday {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();


map.put("code", 10);
map.put("to", 11);
map.put("joy", 12);


if (! map.isEmpty()) {
Map.Entry<String, Integer> entry = map.entrySet().iterator().next();
System.out.println(entry);
}
}
}

如果你真的想要你建议的 API,你可以子类化 HashMap 并且跟踪 List 中的键。我不明白这有什么意义,但它能给你你想要的。如果您解释预期的用例,也许我们可以想出一个更好的解决方案。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@SuppressWarnings("unchecked")
public class IndexedMap extends HashMap {


private List<Object> keyIndex;


public IndexedMap() {
keyIndex = new ArrayList<Object>();
}


/**
* Returns the key at the specified position in this Map's keyIndex.
*
* @param index
*            index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException
*             if the index is out of range (index < 0 || index >= size())
*/
public Object get(int index) {
return keyIndex.get(index);
}


@Override
public Object put(Object key, Object value) {


addKeyToIndex(key);
return super.put(key, value);
}


@Override
public void putAll(Map source) {


for (Object key : source.keySet()) {
addKeyToIndex(key);
}
super.putAll(source);
}


private void addKeyToIndex(Object key) {


if (!keyIndex.contains(key)) {
keyIndex.add(key);
}
}


@Override
public Object remove(Object key) {


keyIndex.remove(key);
return super.remove(key);
}
}

编辑: 我故意没有深入研究这个通用的一面..。

获取值,将其转换为数组,获取数组的第一个元素:

map.values().toArray()[0]

W.

import java.util.*;


public class Friday {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();


map.put("code", 10);
map.put("to", 11);
map.put("joy", 12);


if (! map.isEmpty()) {
Map.Entry<String, Integer> entry = map.entrySet().iterator().next();
System.out.println(entry);
}
}
}

这种方法不起作用,因为您使用的是 HashMap,我假设在这种情况下使用 LinkedHashMap 将是正确的解决方案。

跌跌撞撞地来到这里寻找同样的东西... 然后我想起了 番石榴图书馆Iterables课程。

获取“ first”元素: Iterables.getFirst( someMap.values(), null );。< br/> 本质上与 Map.values().iterator().next()相同,但是也允许您在 Map 中没有任何值的情况下指定默认值(在本例中为 null)。

Iterables.getLast( someMap.values(), null );返回 Map 中的最后一个元素。

如果存在,则 Iterables.get( someMap.values(), 7, null );返回 Map 中的第7个元素,否则返回默认值(在本例中为 null)。

请记住,HashMaps 不是订购的... ... 所以不要期望 Iterables.getFirst返回您在那里抛出的第一个项目... ... Iterables.getLast也是如此。不过,获取 映射值可能有用。

可能不值得为此添加 Guava 库,但是如果您正好在使用该库中的其他一些很酷的实用程序..。

我得到了答案: (很简单)

取一个数组列表,然后对其进行强制转换,找到数组列表的大小。 这就是:

    ArrayList count = new ArrayList();
count=(ArrayList) maptabcolname.get("k1"); //here "k1" is Key
System.out.println("number of elements="+count.size());

它会显示大小。(给出建议)。它的工作。

如果你使用的是 Java8,它和 FindFirst ()一样简单:

举个简单的例子:

Optional<Car> theCarFoundOpt = carMap.values().stream().findFirst();


if(theCarFoundOpt.isPresent()) {
return theCarFoundOpt.get().startEngine();
}
map<string,string>m;
auto it=m.begin();//get iterator to the first element of map(m)
return m->first;//return first string(1st string in map<string,string>m)
//Incase you want the second string
//you can use return m->second(2st string in map<string,string>m)
//if you want to iterate the whole map you can use loop
for(auto it:m)//m is a map
cout<<it->first<<endl;

为了获得 Hash map 的第一个元素,你可以在 kotlin 中使用下面的代码:

val data : Float = hashMap?.get(hashMap?.keys?.first())

如果你使用的是 Java8或更高版本,你可以这样做:

return hashMapObject.entrySet().stream().findFirst().orElse(null) // return null if the map is empty

您可以使用来自番石榴的 Iterables。

Iterables.getOnlyElement(map.keySet()); // To fetch the only key
Iterables.getOnlyElement(map.values()); // To fetch the only value
Iterables.getOnlyElement(map.entrySet()); // To fetch the Map.Entry pair