热线电话:13121318867

登录
2019-02-19 阅读量: 726
拆分Map的键并使用新键和关联值创建新Map

我有一个List的Objects是他们中的每一个包含X,Y值(Doubles)和名称String。由于我有多个与坐标对应的相同名称的条目,我想将每个名称链接到所有坐标,我通过创建Map类型来设法做到这一点 <String, List<Object>>

输出示例:

One [[0.1,0.1,0.1],[0.2,0.3,0.4]]

One,Two [[0.1,0.1] ,[0.4,0.5]]

One,Two,Three [[0.1,0.1] ,[0.6,0.7]]

我现在要做的是将名称拆分为逗号,并实现以下结果:

One [[0.1,0.1,0.1,0.1,0.1,0.1],[0.2,0.3,0.4,0.5,0.6,0.7]]

Two [[0.01,0.01,0.01,0.01] ,[0.4,0.5,0.6,0.7]]

Three [[0.01,0.01] ,[0.6,0.7]]

我的代码是:

Map<String, List<Coordinates>> newList = coordinateList.stream()

.collect(Collectors.groupingBy(Coordinates::getName));

这创造了第一个Map。

为了做第二部分,我尝试了以下各种组合,但没有运气:

newList.entrySet().stream()

.flatMap(entry -> Arrays.stream(entry.getKey().split(","))

.map(s -> new AbstractMap.SimpleEntry<>(s, entry.getValue())))

.collect(Collectors.groupingBy(Map.Entry::getKey,

Collectors.flatMapping(entry -> entry.getValue().stream(), Collectors.toList())));

我得到的错误是:

The method flatMapping((<no type> entry) -> {}, Collectors.toList()) is undefined for the type Collectors

请注意,通过更改flatMapping为mapping工作,但不解决问题。

解决办法:没有使用java9。如果你使用的是Java9,那么以前的方法Collectors.flatMapping就可以了。但我仍然没有看到在Map.Entry这里创造一个新的任何意义。看看这个解决方案。

private static final Pattern COMMA_DELIMITER = Pattern.compile(",\\s*");

Map<String, Set<Coordinate>> nameToCoordinates = coordinates.stream()

.flatMap(

c -> COMMA_DELIMITER.splitAsStream(c.getName())

.map(n -> new Coordinate(n, c.getX(), c.getY())))

.collect(Collectors.groupingBy(Coordinate::getName, Collectors.toSet()));

0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子