获取LinkedHashMap的中间个对象
时间: 2023-07-27 20:13:22 浏览: 87
Java岗面试题大全.pdf
LinkedHashMap是一个有序的HashMap,可以通过迭代器或者转换成List来获取其中间的元素。
方法一:使用迭代器
```java
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
int i = 0;
int mid = map.size() / 2;
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
if (i == mid) {
System.out.println(entry.getValue());
break;
}
i++;
}
```
方法二:转换成List
```java
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
List<Map.Entry<Integer, String>> list = new ArrayList<>(map.entrySet());
int mid = list.size() / 2;
System.out.println(list.get(mid).getValue());
```
阅读全文