流用于从带计数器的列表计算地图

问题描述

我有以下 for 循环,我想用一个简单的 Java 8 流语句替换它:

List<String> words = new ArrayList<>("a","b","c");
Map<String,Long> wordToNumber = new LinkedHashMap<>();
Long index = 1L;

for (String word : words) {
  wordToNumber.put(word,index++);
}

我基本上想要每个单词的排序映射(按插入顺序)到其编号(在每个 for 循环中递增 1),但如果可能的话,使用 Java 8 流可以做得更简单。

解决方法

以下应该可以工作(虽然不清楚为什么需要 Long,因为 List 的大小是 int

Map<String,Long> map = IntStream.range(0,words.size())
    .boxed().collect(Collectors.toMap(words::get,Long::valueOf));

如果 words 列表中没有重复项,则上述代码有效。

如果有可能出现重复词,需要提供一个合并函数来选择应该存储在map中的哪个索引(第一个或最后一个)

Map<String,words.size())
    .boxed().collect(
        Collectors.toMap(words::get,Long::valueOf,(w1,w2) -> w2,// keep the index of the last word as in the initial code
        LinkedHashMap::new // keep insertion order
    ));

类似地,可以通过流words并使用外部变量来增加索引来构建地图(可以使用AtomicLonggetAndIncrement()代替long[]):

long[] index = {1L};
Map<String,Long> map = words.stream()
    .collect(
        Collectors.toMap(word -> word,word -> index[0]++,// keep the index of the last word
        LinkedHashMap::new // keep insertion order
    ));
,
   Map<String,Long> wordToNumber = 
   IntStream.range(0,words.size())
            .boxed()
            .collect(Collectors.toMap(
                    words::get,x -> Long.valueOf(x) + 1,(left,right) -> { throw new RuntimeException();},LinkedHashMap::new
            ));

您可以替换该 (left,right) -> { throw new RuntimeException();},具体取决于您希望如何合并两个元素。

,

略有不同的解决方案。 Integer::max 是合并函数,如果同一个词出现两次,它就会被调用。在这种情况下,它选择最后一个位置,因为这实际上是问题中的代码示例所做的。

@Test
public void testWordPosition() {
    List<String> words = Arrays.asList("a","b","c","b");
    AtomicInteger index = new AtomicInteger();
    Map<String,Integer> map = words.stream()
            .map(w -> new AbstractMap.SimpleEntry<>(w,index.incrementAndGet()))
            .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,Integer::max));
    System.out.println(map);
}

输出:

{a=1,b=4,c=3}

编辑:

在评论中加入 Alex 的建议,它变成:

@Test
public void testWordPosition() {
    List<String> words = Arrays.asList("a","b");
    AtomicLong index = new AtomicLong();
    Map<String,Long> map = words.stream()
            .collect(Collectors.toMap(w -> w,w -> index.incrementAndGet(),Long::max));
    System.out.println(map);
}
,

我基本上想要每个单词的排序映射(按插入顺序)到它的 数字(在每个 for 循环中增加 1),但做得更简单, 如果可能,使用 Java 8 流。

您可以使用以下 Stream 简洁地进行操作:

AtomicLong index = new AtomicLong(1);
words.stream().forEach(word -> wordToNumber.put(word,index.getAndIncrement()));

个人认为

Map<String,Long> wordToNumber = new LinkedHashMap<>();
for(int i = 0; i < words.size(); i++){
    wordToNumber.put(words.get(i),(long) (i + 1));
}

Map<String,Long> wordToNumber = new LinkedHashMap<>();
for (String word : words) {
    wordToNumber.put(word,index++);
}

足够简单。