List<List<Integer>> 中第二个list下标相同之和组成一个List<Integer>
时间: 2023-07-09 18:53:13 浏览: 58
可以使用一个 Map<Integer, Integer> 来记录每个下标出现的次数,然后再遍历 Map 构建结果 List。具体实现可以参考下面的代码:
```java
public List<Integer> sumOfSameIndex(List<List<Integer>> list) {
Map<Integer, Integer> map = new HashMap<>();
for (List<Integer> lst : list) {
for (int i = 0; i < lst.size(); i++) {
map.put(i, map.getOrDefault(i, 0) + lst.get(i));
}
}
List<Integer> result = new ArrayList<>(map.values());
return result;
}
```
首先遍历输入的 List<List<Integer>>,对于每个列表 lst,再遍历它的每个元素,将它们的值累加到 map 中对应下标的计数器上。最后将 map 中所有计数器的值构建成结果 List 并返回即可。
相关问题
java List<String>转map,key为下标
可以使用Java 8中的Stream API和Collectors.toMap()方法将List<String>转换为Map<Integer, String>,其中Integer为下标,String为List中的元素。
代码示例:
```
List<String> list = Arrays.asList("a", "b", "c", "d");
Map<Integer, String> map = IntStream.range(0, list.size())
.boxed()
.collect(Collectors.toMap(Function.identity(), list::get));
```
解释一下上面的代码:
- IntStream.range(0, list.size())会生成一个从0到list.size()-1的整数流。
- .boxed()将IntStream转换为一个Stream<Integer>。
- Collectors.toMap(Function.identity(), list::get)将Stream<Integer>转换为Map<Integer, String>,其中key为元素的下标,value为List中的元素。其中Function.identity()方法返回一个恒等函数,其作用是返回输入的对象本身。
注意事项:
- 如果List中有重复的元素,则会抛出IllegalStateException异常。
- 如果想要在转换过程中处理重复的键,可以使用Collectors.toMap()方法的第三个参数来指定处理冲突的方式。
给我用Java写一个二分查询list中最大的数的下标,
当然可以!下面是用 Java 实现二分查找列表中最大数的索引的示例代码:
```java
import java.util.List;
public class BinarySearchExample {
public static int binarySearchMaxIndex(List<Integer> list) {
int left = 0;
int right = list.size() - 1;
int maxIndex = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (list.get(mid) > list.get(maxIndex)) {
maxIndex = mid;
}
if (list.get(mid) > list.get(mid + 1)) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return maxIndex;
}
public static void main(String[] args) {
List<Integer> list = List.of(1, 3, 5, 7, 9, 8, 6, 4, 2);
int maxIndex = binarySearchMaxIndex(list);
System.out.println("Max index: " + maxIndex);
}
}
```
在这个示例代码中,我们使用了经典的二分查找算法。首先,我们初始化左边界 `left` 为列表的起始位置,右边界 `right` 为列表的结束位置。同时,我们还定义了一个 `maxIndex` 变量,用于保存当前找到的最大数的索引。
然后,我们进入一个循环,直到左边界大于右边界。在每次循环中,我们首先计算出中间位置 `mid`,然后通过比较 `list.get(mid)` 和 `list.get(maxIndex)` 的值,更新 `maxIndex`。接着,我们根据 `list.get(mid)` 和 `list.get(mid + 1)` 的大小关系,调整左边界和右边界的位置。
最终,循环结束后,`maxIndex` 中保存的就是列表中最大数的索引。在示例的 `main` 方法中,我们给定了一个示例列表,并调用 `binarySearchMaxIndex` 方法来获取最大数的索引,并将结果打印输出。
希望这个示例代码对你有帮助!如果有任何问题,请随时问我。