I'm trying to get keys and values list from a list of objects using stream and collectorts but I don't know if it is possible.
I have this class:
public class MyObject {
private int key1;
private String key2;
private String key3;
public int getKey1() { return key1; }
public void setKey1(int key1) { this.key1 = key1; }
public String getKey2() { return key2; }
public void setKey2(String key2) { this.key2 = key2; }
public String getKey3() { return key3; }
public void setKey3(String key3) { this.key3 = key3; }
}
I would like to process a list of this object and get all values and all keys separated by commas.
List<MyObject> objectList = myObjectList;
String keys = objectList.stream().collect(Collectors.joining(", ","(", ")"));
String values = Collections.nCopies(objectList.size(), "?").stream().collect(Collectors.joining(", ", " (", ")"));
Does anyone know if it is possible? or should I try other option?
答案 0 :(得分:7)
对于Stream<MyObject>
的每个元素,您可以Stream<String>
和Stream#flatMap
创建Stream.of
*其键**:
String keys = objectList
.stream()
.flatMap(o -> Stream.of(o.getKey1(), o.getKey2(), o.getKey3()).map(Object::toString))
.collect(Collectors.joining(",", "(", ")"));
*由于某些字段(键)不是String
类型,Stream<Object>
可以由Stream<String>
转换为Stream#map(Object::toString)
。
**如果您有吸气剂,则可以使用相同值。
进一步说,我会为类定义一个List
提取器(Function<MyObject, String>
)(可以有一个静态方法来返回此列表):
public static List<Function<MyObject, String>> getExtractors() {
return Arrays.asList(
o -> String.valueOf(o.getKey1()),
MyObject::getKey2,
MyObject::getKey3
);
}
.flatMap(o -> getExtractors().stream().map(extractor -> extractor.apply(o)))