arrays - 如何将 String[] 转换为 Map,并将数组索引作为 java lambda 中的求和值?

标签 arrays algorithm lambda java-8 hashmap

我有以下内容

new ConstructStateMachine(new String[] {
      "a", "b", "c", "aa", "d", "b"
}, 1, 5);

我想把这个数组转换成 Map<String, Integer> .

因此字符串将数组中的字符串元素作为我映射中的键,值将作为整数列表的数组索引作为值。

我还需要保留重复的键,但是当然这在Map中是不可能的,但是解决方案是我们忽略重复的键,但是我们将重复键的值汇总为,而不是List我们有Integer作为值重复键的所有值的总和。

假设我们有这张表:

indices | 0 | 1 | 2 | 3  | 4 | 5 |
item    | a | b | c | aa | d | b |
value   | 1 | 2 | 3 | 4  | 5 | 6 |

所以我们的 map 应该保留以下内容:

// pseudo-code
Map<String, Integer> dictionary = new HashMap<>(
   ("b"  => 8) // because "b" appeared in index 1 and 5
   ("c"  => 3)
   ("aa" => 4)
   ("d"  => 5)
);

我的不完整解决方案:

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


// I thought of doing an intersection of two arrays and get the value from there
// but that just made things more complicated
String[] a = (Arrays.stream(dictionary)
  .filter(x - > Arrays.stream(newDis)
    .anyMatch(y - > Objects.equals(y, x))
  )
).toArray(String[]::new);


// in here, I tried looping and created the value that starts from 1 to 6, rather than
// from 0 to 5
IntStream.range(0, this.newDis.length).forEach(idx - > {
  List<Integer> currentValue = table.computeIfAbsent(newDis[idx], k - > new ArrayList<>());
  currentValue.add(idx + 1);
});

但我无法将我的字符串数组转换为 Map<String, Integer>

最佳答案

String[] array = new String[] {"a", "b", "c", "aa", "d", "b"};
Map<String, Integer> result =
    IntStream.range(0, array.length)
             .boxed()
             .collect(Collectors.toMap(i -> array[i], i -> i + 1, Integer::sum));

或者,使用一个简单的循环,使代码更易于阅读和直观,IMO:

Map<String, Integer> result = new HashMap<>();
for (int i = 0; i < array.length; i++) {
    result.merge(array[i], i + 1, Integer::sum);
}

关于arrays - 如何将 String[] 转换为 Map,并将数组索引作为 java lambda 中的求和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46942690/

相关文章:

c - 列表元素而不是数组 C

javascript - 如何通过属性搜索嵌套对象中的对象并返回带有父对象的键和值的对象?

algorithm - 教授递归技术的最佳方法是什么?

c++ - 将 lambda 分配给 std::function

java - _(下划线)是保留关键字

java - 为什么 java 中的 String.Split(regex) 返回的元素数组的大小小于实际存在的元素大小?

javascript - 从二维数组中获取 JavaScript 中的最小值和最大值

algorithm - 在非图行中找到所有可能解决方案的递归算法

C# - For 循环和 lambda 表达式

Java 2d 数组列打印两次