Let's Example I have String s = "Rahul Kumar" I need to have Rahul as a output using java8
Actual Requirement, I do have a list of Trip Object, I want to set driverName property as only first name to each Trip Object and return that list?
System.out.println( someStringValue.subSequence(0, someStringValue.indexOf(' ')));
I'm getting trouble to incorporate this code into the listOfTrip. If I'm doing like this,
List<CharSequence> list = listOfTrips.stream().map(e -> e.getDriverName().subSequence(0, someStringValue.indexOf(' '))).collect(Collectors.toList()); System.out.println(list);
Here, With this, The return type is wrong and it is not fetching only first name out of full name.
CodePudding user response:
Below will give you the proper result:
List<CharSequence> list2 = listOfTrips.stream()
.map(m->m.getDriverName().substring(0,m.getDriverName().indexOf(' ')))
.collect(Collectors.toList());
CodePudding user response:
Please try this also once:
String s = "Rahul Kumar";
Optional<String> beforeWhiteSpace = Pattern.compile(" ").splitAsStream(s).collect(Collectors.toList()).stream().findFirst();