Stream代码的一个范例

2019-07-17  本文已影响0人  怕水河马

写Stream也有一段时间了,这段是一个典型代码,记录一下


public ConcurrentMap>listSpecfiedPath(String path) {

return Arrays.asList(path.split(","))

.parallelStream()

.map(s -> {

NodePath nodePath =new NodePath();

                nodePath.setOriginPath(s);

                String finalPath =START_PATH.endsWith("/") ?START_PATH + s :START_PATH +"/" + s;

                //有环境变量,优先读取环境变量路径,否则读取当前路径

                boolean b =zkClient.exists(finalPath +"/" +profile);

                if (!b) {

b =zkClient.exists(finalPath);

                }else {

nodePath.setFinalPath(finalPath +"/" +profile);

                    return nodePath;

                }

if (!b) {

nodePath.setFinalPath(null);

                }else {

nodePath.setFinalPath(finalPath);

                }

return nodePath;

            })

.filter(s -> s.getFinalPath() !=null)

.flatMap((Function>>) s -> {

//获取节点下的子节点list

//不包含存在子节点的节点

                List children =zkClient.getChildren(s.getFinalPath());

                return children.parallelStream().filter(

childPath ->zkClient.countChildren(s.getFinalPath() +"/" + childPath) ==0)

.map(

childPath -> {

PropertyPath propertyPath =new PropertyPath();

                                    propertyPath.setFullPath(s.getFinalPath() +"/" + childPath);

                                    propertyPath.setPropertyPath(childPath);

                                    return new AbstractMap.SimpleEntry<>(s, propertyPath);

                                });

            })

.map((Function, Map.Entry>>)

stringStringEntry -> {

String value =zkClient.readData(stringStringEntry.getValue().getFullPath());

                        return new AbstractMap.SimpleEntry<>(

stringStringEntry.getKey(),

                                new AbstractMap.SimpleEntry<>(stringStringEntry.getValue(), value)

);

                    })

.filter(stringEntryEntry -> StringUtils.isNotBlank(stringEntryEntry.getValue().getValue()))

.map((Function>, Map.Entry>>) stringEntryEntry ->new AbstractMap.SimpleEntry<>(

stringEntryEntry.getKey(),

                    new AbstractMap.SimpleEntry<>(

stringEntryEntry.getValue().getKey().getPropertyPath(),

                            stringEntryEntry.getValue().getValue())))

.collect(Collectors.toConcurrentMap(

stringEntryEntry -> stringEntryEntry.getKey(),

                    stringEntryEntry -> {

ConcurrentHashMap retMap =new ConcurrentHashMap<>();

                        retMap.put(stringEntryEntry.getValue().getKey(), stringEntryEntry.getValue().getValue());

                        return retMap;

                    },

                    (stringStringConcurrentHashMap, stringStringConcurrentHashMap2) -> {

stringStringConcurrentHashMap.putAll(stringStringConcurrentHashMap2);

                        return stringStringConcurrentHashMap;

                    }));

}

说实话,会这么写,只是因为能简单帮我解决并发的问题,可读性……其实并不算好

上一篇 下一篇

猜你喜欢

热点阅读