将对象的 ArrayList 转换为该对象的 ArrayList Java 中的字符串名称
我有一个 User 对象的 ArrayList。现在我只需要这些用户名的 ArrayList。有没有办法在整个 ArrayList 上使用 toString() 并将其转换为字符串名称的 ArrayList,而不是在 for 循环中执行此操作?我还重写了 User 类中的 toString ,以便它返回用户名,并且我尝试了 ArrayList
I have an ArrayList of User objects. Now I need the ArrayList of these user's names only. Is there a way to use toString()
on entire ArrayList and convert it to ArrayList of String names rather than doing this in for loop? I have also overridden toString in User class so it returns user's name, and I have tried ArrayList <String> names = usersList.toString()
but it didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 Google Collections API 执行此操作:
该库已重命名为 Guava 。
在 Java 8 中,使用流和方法引用,即使不使用 Guava,您现在也可以实现相同的目标:
You can do this using the Google Collections API:
The library has been renamed to Guava.
With Java 8, using streams and method references you can now achieve the same thing even without using Guava:
对象# toString()
返回一个String
,而不是ArrayList
。那是你的问题。你真的需要循环它。绝对没有理由反对循环。如果代码以某种方式困扰您,只需将其隐藏在某个实用方法中即可;)使用 Java 8,您可以使用 lambda 表达式、流和方法引用来简化代码。
以下内容
然后可以将
缩短为 like顺便说一句,您也可以将
for
放在一行中:但是对于初学者来说,它可能无法直接理解。
The
Object#toString()
returns aString
, not anArrayList
. That's your problem. You really need to loop over it. There's absolutely no reason for an aversion against looping. Just hide it away in some utility method if the code is bothering you somehow ;)With Java 8, you can use lambda expressions, streams, and method references to simplify your code.
The following
can then be shortened to like
By the way, you can also put the
for
in a single line:It may however not be directly understandable for starters.
总之:不。你需要的是一个 map 函数,它Java 中还没有(正如 BalusC 指出的那样)。您可以自己编写类似的内容,但无论如何您最终都会迭代列表中的每个元素。
In a word: No. What you need is a map function, which you don't have in Java (yet, as BalusC points out). You can write something similar yourself, but you'll end up iterating over each element in your List regardless.
那里。一行,您可以将其与您将来拥有的任何对象集合一起重复使用。
There. One line, and you can reuse it with whatever collection of objects you have in the future.