使用 Streams 将对象列表转换为映射

我有一个 A 类对象列表:


List<A> list;

class A {

    String name;

    String lastname;

    //Getter and Setter methods

}

我想将此列表转换为从名称到一组姓氏的映射:


Map<String, Set<String>> map;

例如,对于以下列表:


约翰·阿彻、约翰·阿盖特、汤姆·凯南宁、汤姆·巴伦、辛迪·金


地图将是:


约翰 -> {阿切尔、玛瑙}、汤姆 -> {凯纳宁、贫瘠}、辛迪 -> {国王}


我尝试了以下代码,但它返回从名称到 A 类对象的映射:


list.stream.collect(groupingBy(A::getFirstName, toSet()));


神不在的星期二
浏览 122回答 2
2回答

呼如林

Map< String, Set<String>> map = list.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.groupingBy(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; A::getFirstName, Collectors.mapping(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; A::getLastName, Collectors.toSet())));您走在正确的轨道上,您需要使用:Collectors.groupingBy按 进行分组firstName。然后使用下游收集器作为 的Collectors.mappping第二个参数Collectors.groupingBy来映射到lastName.然后最后Set<String>通过调用将其收集到 a 中Collectors.toSet:

PIPIONE

你从来没有告诉收集者提取姓氏。我想你需要类似的东西list.stream&nbsp; .collect(groupingBy(&nbsp; &nbsp; A::getFirstName, // The key is extracted.&nbsp; &nbsp; mapping(&nbsp; // Map the stream of grouped values.&nbsp; &nbsp; &nbsp; A::getLastName, // Extract last names.&nbsp; &nbsp; &nbsp; toSet()&nbsp; // Collect them into a set.)));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java