Java 从列表中提取值(非键)<;地图<;字符串,字符串>>;,并将其展平为一个列表<;字符串>;

Java 从列表中提取值(非键)<;地图<;字符串,字符串>>;,并将其展平为一个列表<;字符串>;,java,list,java-8,java-stream,Java,List,Java 8,Java Stream,如何从列表中提取值(而不是键),并将其展平到列表 i、 e.尝试了以下操作,但无效 List<Map<String,String>> mapList = .... ; List<String> valueList = mapList.stream() .map(o -> o.getValue()) .collect(Colle

如何从
列表
中提取值(而不是键),并将其展平到
列表

i、 e.尝试了以下操作,但无效

List<Map<String,String>> mapList = .... ;

List<String> valueList = mapList.stream()
                                .map(o -> o.getValue())
                                .collect(Collectors.toList());
列表映射列表=;
List valueList=mapList.stream()
.map(o->o.getValue())
.collect(Collectors.toList());
我还想按给定的键过滤结果。

您的意思是:

List<String> valueList = mapList.stream()
        .flatMap(a -> a.values().stream())
        .collect(Collectors.toList());

使用
.flatMap

List<Map<String,String>> mapList = new ArrayList<>();

Map<String, String> mapOne = new HashMap<>();
mapOne.put("1", "one");
mapOne.put("2", "two");

Map<String, String> mapTwo = new HashMap<>();
mapTwo.put("3", "three");
mapTwo.put("4", "four");

mapList.add(mapOne);
mapList.add(mapTwo);

List<String> allValues = mapList.stream()
    .flatMap(m -> m.values().stream())
    .collect(Collectors.toList()); // [one, two, three, four]
List-mapList=new-ArrayList();
Map mapOne=newhashmap();
mapOne.put(“1”、“1”);
mapOne.put(“2”、“2”);
Map mapTwo=新的HashMap();
地图2.put(“3”、“3”);
地图2.put(“4”、“4”);
mapList.add(mapOne);
mapList.add(maptoo);
List allValues=mapList.stream()
.flatMap(m->m.values().stream())
.collect(Collectors.toList());//[一,二,三,四]
试试看

List valueList=mapList.stream()
.flatMap(map->map.entrySet().stream())
.filter(entry->entry.getKey().equals(“KEY”))
.map(map.Entry::getValue)
.collect(Collectors.toList());

您试图映射到o.getValue()的对象是map类型(它没有函数getValue()),而不是map.Entry(它将有这样一个函数)。您可以通过函数o.values()获得一组值

然后,您可以从该集合中获取流,并按如下方式展平生成的流:

List<String> valueList = mapList.stream()
                         .map(o -> o.values().stream())
                         .flatMap(Function.identity())
                         .collect(Collectors.toList());
List valueList=mapList.stream()
.map(o->o.values().stream())
.flatMap(函数.identity())
.collect(Collectors.toList());

谢谢,我刚刚意识到这会得到所有的值,我只需要一组。如果我想指定一个键,例如我有“id”和“firstName”,但只想要“firstName”。添加一个过滤器“``List valueList=mapList.stream().flatMap(I->I.entrySet().stream().filter(entry->entry.getKey().equals(“firstName”))。map(entry->entry.getValue())。collect(collector.toList()); ```如果我想指定一个键,例如我有“id”和“firstName”,但只想要“firstName”,该怎么办。现在,这抓住了所有的价值观(对不起,我错了…)
    List<String> valueList = mapList.stream()
            .flatMap(map -> map.entrySet().stream())
            .filter(entry -> entry.getKey().equals("KEY"))
            .map(Map.Entry::getValue)
            .collect(Collectors.toList());
List<String> valueList = mapList.stream()
                         .map(o -> o.values().stream())
                         .flatMap(Function.identity())
                         .collect(Collectors.toList());