complex operation using stream api in java

user7851946 :

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?

Eran :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121204&siteId=1