如何在映射后将前缀添加到列表中的每个字符串?

huangapple go评论60阅读模式
英文:

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&lt;String&gt; mappedListWithPrefix(List&lt;MyClass&gt; list) {

  List&lt;String&gt; op = list.stream().map(MyClass::getUid).collect(Collectors.toList());//step 1
  op.replaceAll(s -&gt; &quot;ROLE_&quot;+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&lt;String&gt; op = list.stream()
   .map(MyClass::getUid)
   .map(s -&gt; &quot;ROLE_&quot; + s)
   .collect(Collectors.toList());

or just do both operations in one map call:

List&lt;String&gt; op = list.stream()
   .map(o -&gt; &quot;ROLE_&quot; + o.getUid())
   .collect(Collectors.toList());

Which one to pick is mostly down to personal preference.

huangapple
  • 本文由 发表于 2020年9月16日 19:48:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63919434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定