Hashmap with Streams in Java 8 Streams to collect value of Map

后端 未结 6 1946
悲&欢浪女
悲&欢浪女 2021-01-30 19:59

Let consider a hashmap

Map id1 = new HashMap();

I inserted some values into both hashmap.

For

6条回答
  •  佛祖请我去吃肉
    2021-01-30 20:21

    You can also do it like this

    public Map> getpartitionMap(List studentsList) {
    
        List> allPredicates = getAllPredicates();
        Predicate compositePredicate =  allPredicates.stream()
                                 .reduce(w -> true, Predicate::and)
         Map> studentsMap= studentsList
                    .stream()
                    .collect(Collectors.partitioningBy(compositePredicate));
        return studentsMap;
    }
    
    public List getValidStudentsList(Map> studentsMap) throws Exception {
    
        List validStudentsList =  studentsMap.entrySet()
                 .stream()
                 .filter(p -> p.getKey() == Boolean.TRUE)
                 .flatMap(p -> p.getValue().stream())
                 .collect(Collectors.toList());
    
        return validStudentsList;
    }
    
    public List getInValidStudentsList(Map> studentsMap) throws Exception {
    
        List invalidStudentsList = 
                 partionedByPredicate.entrySet()
                 .stream()
                 .filter(p -> p.getKey() == Boolean.FALSE)
                 .flatMap(p -> p.getValue().stream())
                 .collect(Collectors.toList());
    
        return invalidStudentsList;
    
    }
    

    With flatMap you will get just List instead of List>.

    Thanks

提交回复
热议问题