Java 8 toMap IllegalStateException Duplicate Key [英] Java 8 toMap IllegalStateException Duplicate Key

查看:974
本文介绍了Java 8 toMap IllegalStateException Duplicate Key的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件包含以下格式的数据

I have a file which contains data in the following format

1
2
3

我想将其加载到地图 {(1-> 1) ,(2-> 1),(3-> 1)}

这是Java 8代码,

This is the Java 8 code,

Map<Integer, Integer> map1 = Files.lines(Paths.get(inputFile))
                .map(line -> line.trim())
                .map(Integer::valueOf)
                .collect(Collectors.toMap(x -> x, x -> 1));

我收到以下错误

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 1

如何修复此错误?

推荐答案

如果文件中没有重复项,代码将会运行。

The code will run if there are no duplicates in the file.

Map<Integer, Integer> map1 = Files.lines(Paths.get(inputFile))
            .map(String::trim)
            .map(Integer::valueOf)
            .collect(Collectors.toMap(x -> x, x -> 1));

如果有重复项,请使用以下代码获取该密钥的文件中出现的总数。

If there are duplicates use the following code to get the total number of occurrences in the file for that key.

Map<Integer, Long> map1 = Files.lines(Paths.get(inputFile))
            .map(String::trim)
            .map(Integer::valueOf)
            .collect(Collectors.groupingBy(x -> x, Collectors.counting());

这篇关于Java 8 toMap IllegalStateException Duplicate Key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆