假设我有一个Stream<String>,用什么最简洁的方法可以获得一个Stream<CustomType>,其中Stream<CustomType>的每个元素都将Stream<String>的每个元素作为其成员变量之一的值:
例如:
class CustomType {
private String id;
public void setId(String id) {
this.id = id;
}
}
class Test {
public static void main (String... args) {
Stream<String> source = Stream.of("A", "B", "C");
Stream<CustomType> result = source.map(s -> {
CustomType obj = new CustomType();
obj.setId(s);
return obj;
});
}
}有办法缩短这个时间吗?
后来编辑了:寻找一种方法而不是重写CustomType的构造函数,并避免编写手动创建CustomType对象的模板,例如,让Stream为我创建CustomType对象,这样我就可以指定String应该设置的是什么setter (例如:setID())。
发布于 2021-11-05 17:06:42
如果可以更改自定义类型的构造函数,则可以:
class CustomType {
private String id;
public CustomType(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
}
class Test {
public static void main (String... args) {
Stream<String> source = Stream.of("A", "B", "C");
Stream<CustomType> result = source.map(CustomType::new);
}
}如果不能添加新的构造函数,那么最好的方法是将设置逻辑移出流处理器之外,如下所示:
class Test {
public static void main (String... args) {
Stream<String> source = Stream.of("A", "B", "C");
Stream<CustomType> result = source.map(Test::customTypeWithId);
}
private static CustomType customTypeWithId(String id) {
CustomType obj = new CustomType();
obj.setId(s);
return obj;
}
}发布于 2021-11-05 17:52:49
对于任何CustomType,您都可以这样做。
Stream<String> source = Stream.of("A", "B", "C");
Function<String,CustomType> fnc = (str) -> {
CustomType t = new CustomType();
t.setId(str);
return t;};
Stream<CustomType> stream = customStream(source, fnc);
public static <T> Stream<T> customStream(Stream<String> source,
Function<String, T> fnc) {
Builder<T> builder = Stream.builder();
source.forEach(k -> builder.add(fnc.apply(k)));
return builder.build();
}当然,如果您的自定义类型实现了一个以T setId(String s)作为方法的接口,则会更好。这方面的一个例子是:
interface SetIDInterface<T> {
public T setId(String s);
}
class CustomType implements SetIDInterface<CustomType> {
public String id;
public CustomType setId(String id) {
this.id = id;
return this;
}
}
Stream<String> source = Stream.of("A", "B", "C");
Stream<CustomType> stream = customStream(source, CustomType::new);
public static <T extends SetIDInterface<T>> Stream<T>
customStream(Stream<String> source, Supplier<T> sup) {
Builder<T> builder = Stream.builder();
source.forEach(k -> builder.add(sup.get().setId(k)));
return builder.build();
}https://stackoverflow.com/questions/69856813
复制相似问题