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

如何解决流用于从带计数器的列表计算地图

我有以下 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++);
}

足够简单。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?