Home > Back-end >  How to seperate a list of map of strings according to a key value in the list map?
How to seperate a list of map of strings according to a key value in the list map?

Time:11-14

I have a list of Map of Strings like this

List<Map<String, String>> dataListMap = new ArrayList<>();
Map<String, String> dataMap = new HashMap<String, String>() {
    {
        put("Charged fare", "3");
        put("Trip ID", "1");
        put("Account", "220");
    }
};
dataListMap.add(dataMap);
dataMap = new HashMap<String, String>() {
    {
        put("Charged fare", "5");
        put("Trip ID", "2");
        put("Account", "220");
    }
};
dataListMap.add(dataMap);
dataMap = new HashMap<String, String>() {
    {
        put("Charged fare", "7");
        put("Trip ID", "3");
        put("Account", "230");
    }
};
dataListMap.add(dataMap);
dataMap = new HashMap<String, String>() {
    {
        put("Charged fare", "8");
        put("Trip ID", "4");
        put("Account", "230");
    }
};
dataListMap.add(dataMap);

I want to separate this list by the account number and convert this to two list in side a List<List<Map<String,String>>> Is there an easy way to do that?Please help

CodePudding user response:

List<List<Map<String, String>>> groupedByIds =
        new ArrayList<>(dataListMap.stream()
                .collect(Collectors.groupingBy(i -> i.get("Account")))
                .values());
System.out.println(groupedByIds);

I believe that this is what you asked for but you should try specifying your use case, it can probably be better designed.

Collection<List<Map<String, String>>> accountString = dataListMap.stream().collect(groupingBy(m -> m.get("Account"))).values(); for(List<Map<String, String>> account: accountString){ calculateDailyCap(account); } is it possible to convert this back to only one list?

List<Map<String,String>> regroupedList = groupedByIds.stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toList());
System.out.println(regroupedList);

Yes you can do it with flatmap, but you already have the list at the start why would you do that?

Stream never affects the result of your initial Collection, it always returns new result, so it is safe to reuse the list you had at the start.

CodePudding user response:

I think you need to iterate over the list and push the Maps in two new Lists of Maps according to their Account number.

However without knowing the precise task you're trying to achieve, I would consider creating a new class that holds the three attributes you currently contain in your map. That would result it way more robust code, that is also easier to extend in the future.

  • Related