怎么样Collectors.groupingBy()。我认为您仍然可以改进字符串的错误部分集并加入它们,以下代码的输出是:
{false=[SomeException, ReallyBadProblem], true=[3, 5]}
代码示例:
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toSet;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Validation<String,Integer> a = new Validation<>(true, null, 3);
Validation<String,Integer> b = new Validation<>(true, null, 5);
Validation<String,Integer> c = new Validation<>(false, "SomeException", null);
Validation<String,Integer> d = new Validation<>(false, "ReallyBadProblem", null);
//Stream.of(a,b,c).collect(Collectors.groupingBy(v->v.isValid(), v->v.));
TreeMap<Boolean, Set<Object>> map = Stream.of(a,b,c,d).collect((groupingBy(v->v.isValid(), TreeMap::new,
mapping(v-> { return v.isValid() ? v.valid() : v.getError();}, toSet()))));
System.out.println(map);
}
public static class Validation<E, T>{
boolean valid;
T validVal;
String error;
public Validation(boolean valid, String error, T validVal) {
super();
this.valid = valid;
this.error = error;
this.validVal = validVal;
}
/**
* @return the valid
*/
public boolean isValid() {
return valid;
}
/**
* @param valid the valid to set
*/
public void setValid(boolean valid) {
this.valid = valid;
}
/**
* @return the error
*/
public String getError() {
return error;
}
/**
* @param error the error to set
*/
public void setError(String error) {
this.error = error;
}
public T valid() {
return validVal;
}
}
}