我有一个我想要转换和过滤的Java Map.作为一个简单的例子,假设我想将所有值转换为整数然后删除奇数条目.
Map<String, String> input = new HashMap<>();
input.put("a", "1234");
input.put("b", "2345");
input.put("c", "3456");
input.put("d", "4567");
Map<String, Integer> output = input.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> Integer.parseInt(e.getValue())
))
.entrySet().stream()
.filter(e -> e.getValue() % 2 == 0)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(output.toString());
Run Code Online (Sandbox Code Playgroud)
这是正确的,并产生: {a=1234, c=3456}
但是,我不禁想知道是否有办法避免.entrySet().stream()两次打电话.
有没有办法可以执行转换和过滤操作,.collect()最后只调用 一次?
假设对象 A 有一个类型为 的字段net.Dialer。我想为对象 A 提供net.Dialer增强Dial方法的自定义实现。这在 Go 中可行吗?我正在尝试使用嵌入式字段,如下所示:
package main
import (
"net"
"fmt"
)
type dialerConsumer struct {
dialer net.Dialer
}
func (dc *dialerConsumer) use() error {
conn, e := dc.dialer.Dial("tcp", "golang.org:http")
if e != nil {
return e
}
fmt.Printf("conn: %s\n", conn)
return nil
}
type customDialer struct {
net.Dialer
}
func main() {
standardDialer := net.Dialer{}
consumer := &dialerConsumer{
dialer: standardDialer,
}
consumer.use()
/*
customDialer := customDialer{
net.Dialer{},
} …Run Code Online (Sandbox Code Playgroud)