如何在Java 8中将对象ArrayList的元素返回为String ArrayList:

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

How to return Objects ArrayList element to String arrayList in java 8

问题

我尝试将Objects Array List元素添加到String Array List中,我正在使用下面的代码,但它显示语法错误。有人可以帮我吗?

List<String> sample = request.getItemList().forEach(object -> {
    return sample.add(object.getProductGroup());
});
英文:

I am trying to add Objects Array List element to String Array List and I am using below code but its showing syntax errors. Can some one help me please?

List&lt;String&gt;sample = request.getItemList().forEach(object-&gt;{
        	return sample.add(object.getProductGroup());
        	});

答案1

得分: 2

以下是翻译好的部分:

使用您现有的代码的工作方式是:

List<String> sample = new ArrayList<>();
request.getItemList().forEach(object -> sample.add(object.getProductGroup()));

但使用 map 操作:

List<String> sample = request.getItemList().stream()
        .map(object -> object.getProductGroup())
        .collect(Collectors.toList());
英文:

The working way with the code you have is

List&lt;String&gt; sample = new ArrayList&lt;&gt;();
request.getItemList().forEach(object -&gt; sample.add(object.getProductGroup()));

But using map operation

List&lt;String&gt; sample = request.getItemList().stream()
        .map(object -&gt; object.getProductGroup())
        .collect(Collectors.tolist());

huangapple
  • 本文由 发表于 2020年4月10日 17:41:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/61137640.html
匿名

发表评论

匿名网友

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

确定