Reputation:
I have a requirement, where I have a string which is comma separated and then I need to read the individual value and create a collection of object using them.
For example my string contains value like foo , bar, baz
and then I need to create three object using them like
Object foo = new Object("foo");
Object bar = new Object("bar");
Object baz = new Object("baz");
There might be multiple spaces before and after the ,
, so I want to remove them as well, so that my object is created with proper string, how can I do this using stream API and single line of code?
Upvotes: 5
Views: 201
Reputation: 394126
I denoted your class as YourClass
, since Object
is already taken.
You can use split
to split the input String
into tokens, and trim
to eliminate the spaces:
List<YourClass> list =
Arrays.stream(inputStr.split(","))
.map(s -> new YourClass(s.trim())
.collect(Collectors.toList());
Upvotes: 7