简体   繁体   中英

How to convert with Java stream List<Map<String,Object>> to List<String> removing part of each Stream

I have a method :

public List<Map<String, Object>> getAllListsExcept() {
        String query = "SELECT Name FROM " + account.getName()
                + " WHERE NOT (Name LIKE '%1234567%')";
        return SQLHelper.getByQuery(query);
    }

return list:

[{name=AQA Chief Officer}, {name=AQA Internal Accounts}, {name=AQA Interactions}, {name=AQA Legacy Planner}, {name=AQA Principal Facilitator}, {name=AQA Regional Program}, {name=cd_AQA Cassattatque}, {name=cd_AQA Kandinskyfugiat}, {name=cd_AQA Raphaelquitester}, {name=cd_AQA Rembrandtanimi}, {name=cd_AQA Seuratest}]

I want to return me List only names without these part: 'name=' Like this:

[{AQA Chief Officer}, {AQA Internal Accounts}, {AQA Interactions}, {AQA Legacy Planner}, {AQA Principal Facilitator}, {AQA Regional Program}, {AQA Cassattatque}, {AQA Kandinskyfugiat}, {AQA Raphaelquitester}, {AQA Rembrandtanimi}, {AQA Seuratest}]

Is it possible not to use a substring?

Thanks

You can use a map from stream to perform this task, it should look like something like this in case your Map has exactly one value

getAllListsExcept().stream().map(hmap->hmap.values().iterator().next())
.collect(Collectors.toList());

You can get the values from Map and use flatMap

List<Object> result = getAllListsExcept().stream()
                                         .map(Map::values)
                                         .flatMap(Collection::stream)
                                         .collect(Collectors.toList());

Is it possible not to use a substring?

Yes, you don't have to use a substring solution. In fact, using a substring solution would not be the best. You can use a stream .

        List<Map<String, Object>> list = List.of(
                Map.of("name", "AQA Chief Officer"),
                Map.of("name", "AQA Internal Accounts"),
                Map.of("name", "AQA Legacy Planner"),
                Map.of("name",
                        "AQA Principal Facilitator"));

        List<String> result = list.stream()
                .flatMap(map -> map.values().stream())
                .map(Object::toString)
                .collect(Collectors.toList());

        result.forEach(System.out::println);

It prints the following.

AQA Chief Officer
AQA Internal Accounts
AQA Legacy Planner
AQA Principal Facilitator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM