Replace anonymous Function with lambda expression

2019-03-03 09:33发布

I'm passing a Function in a Java 8 map operation and Intellij tells me that it can be replaced with a lambda expression. But I don't see how I can do it without creating an intermediate object structure.

Here is what I do :

List<DocumentResult> documentResults = objects.getObject().stream()
                .map(new Function<ObjectType, DocumentResult>() {
                         @Override
                         public DocumentResult apply(ObjectType objectType) {
                             String[] keys = objectType.getStorageKey().getObjectName().split("/");
                             DocumentResult result = new DocumentResult(DocCategories.valueByLabel(keys[1]), DocCategoryGroups.valueByLabel(keys[2]), DocSubCategories.valueByLabel(keys[3]), keys[4], keys[5]);
                             result.setLink(objectType.getTempUrl().getFullUrl());
                             return result;
                         }
                     })
                .collect(Collectors.toList());

And what I think Intellij advise me to do :

List<DocumentResult> documentResults = objects.getObject().stream()
                .map(object -> object.getStorageKey().getObjectName().split("/"))
                .map(tab -> new DocumentResult(DocCategories.valueByLabel(tab[1]), DocCategoryGroups.valueByLabel(tab[2]), DocSubCategories.valueByLabel(tab[3]), tab[4], tab[5]))
                .collect(Collectors.toList());

I don't know a clean way to get the objectType.getTempUrl().getFullUrl() part I retrieved in my anonymous Function, any suggestions?

1条回答
做个烂人
2楼-- · 2019-03-03 09:49

You can always just write

List<DocumentResult> documentResults = objects.getObject().stream()
                .map(objectType -> {
                         String[] keys = objectType.getStorageKey().getObjectName().split("/");
                         DocumentResult result = new DocumentResult(DocCategories.valueByLabel(keys[1]), DocCategoryGroups.valueByLabel(keys[2]), DocSubCategories.valueByLabel(keys[3]), keys[4], keys[5]);
                         result.setLink(objectType.getTempUrl().getFullUrl());
                         return result;
                     })
                .collect(Collectors.toList());

...just using a normal multi-line lambda.

查看更多
登录 后发表回答