英文:
How to append prefix to each string in a list after mapping?
问题
I need to append a prefix "ROLE_" to each string collected after mapping with a string in an object. I have done this in two steps as shown in the method mappedListWithPrefix
:
class MyClass {
String uid;
}
////////
List<String> mappedListWithPrefix(List<MyClass> list) {
List<String> op = list.stream().map(MyClass::getUid).collect(Collectors.toList());//step 1
op.replaceAll(s -> "ROLE_"+s);//step 2
return op;
}
Is there a way to do this in a single step, without using a second list, somewhat like map("ROLE_"+MyClass::getUid)
? (Please note this is just to convey the idea, this mapping won't work)
英文:
I need to append a prefix "ROLE_" to each string collected after mapping with string in an object. I have done this in two steps as showin in method mappedListWithPrefix:
class MyClass {
String uid;
}
////////
List<String> mappedListWithPrefix(List<MyClass> list) {
List<String> op = list.stream().map(MyClass::getUid).collect(Collectors.toList());//step 1
op.replaceAll(s -> "ROLE_"+s);//step 2
return op;
}
Is there a way to do this in a single step, without using a second list, somewhat like map( "ROLE_"+MyClass::getUid) ? (Pls note this is just to convey idea, this mapping wont wrk)
答案1
得分: 4
你可以要么添加第二个map
步骤:
List<String> op = list.stream()
.map(MyClass::getUid)
.map(s -> "ROLE_" + s)
.collect(Collectors.toList());
要么只需在一个map
调用中执行两个操作:
List<String> op = list.stream()
.map(o -> "ROLE_" + o.getUid())
.collect(Collectors.toList());
选择哪个取决于个人偏好。
英文:
You can either add a second map
step:
List<String> op = list.stream()
.map(MyClass::getUid)
.map(s -> "ROLE_" + s)
.collect(Collectors.toList());
or just do both operations in one map
call:
List<String> op = list.stream()
.map(o -> "ROLE_" + o.getUid())
.collect(Collectors.toList());
Which one to pick is mostly down to personal preference.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论