Home > Mobile >  Java 8 - Create map from a filtered Map
Java 8 - Create map from a filtered Map

Time:10-17

I've a 2 classes

class Emp {
    String uri;
    String practice;
}

class Loc {
    String uri;
    String name;
}

Also I've 2 inputs:

List<Emp> empList
Map<String, Loc> locMap; // here key is uri of Loc.

First I want to filter locMap for all uri which are present in empList. That is:

locMap.entrySet()stream().filter(e -> /* e.getKey is present in uri in empList  */)

Then from this filtered output I want to create a new Map which will contain Loc's name as key and practice as value, i.e. Map<name, practice>.

How can I do it in Java 8?

What I've tried so far:

I've followed a long approach.

Convert empList into Map<uri, Emp> filteredEmp;

Then,

locMap.entrySet()stream()
    .filter(e->filteredEmp.containsKey(e.getKey))
    .collect(toMap(e-> e.getValue().getName(), e-> filteredEmp.get(e.getKey())));

CodePudding user response:

If you stick to stream API, then the following should work, though it may be easier to write without stream API.

        final Map<String, String> answers = locMap.entrySet().stream().map(e -> {
        for (Emp emp : empList) {
            if (e.getKey().equals(emp.uri)) {
                return new Map.Entry<String, String>() {

                    @Override
                    public String getKey() {
                        return e.getValue().name;
                    }

                    @Override
                    public String getValue() {
                        return emp.practice;
                    }

                    @Override
                    public String setValue(String value) {
                        return null;
                    }
                    
                };
            }
        }
        return null;
    }).filter(e -> (e != null)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

CodePudding user response:

I would suggest to stream over your list first to simplify the mapping

import java.util.AbstractMap.SimpleEntry;

....


Map<String,String> result =
     empList.stream()
            .filter(emp -> locMap.containsKey(emp.getUri()))
            .map(emp -> new SimpleEntry<>(locMap.get(emp.getUri()).getName(), emp.getPractice()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a,b) -> b));
  • Related