Joy16 Joy16 - 1 month ago 5
Java Question

String list get an item starting without loop

I have a array list contains thousands of data.

For Example:

List<String> custNames = new ArrayList<String>();
custNames.add("John");
custNames.add("Tom");
custNames.add("Bart");
custNames.add("Tim");
custNames.add("Broad");


Now I want to get count of names only starting with 'T'. I used looping mechanism for my solution.

List<String> filterNames = new ArrayList<String>();
String nameStarts="T";
for(int i=0;i<custNames.size();i++)
{
if(custNames.get(i).toLowerCase().startsWith(nameStarts.toLowerCase()))
{
filterNames.add(custNames.get(i));
}
}
System.out.println(filterNames.size());


But I have very large collection of data in this custNames list.
Is there any different solution without using loop?

Thanks.

Answer

There is very good solution from Java 8 for your problem.

Try this,

long filterNameCount = custNames
        .stream()
        .parallel() 
        .filter((s) -> s.startsWith(nameStarts.toLowerCase()))
        .count();

System.out.println(filterNameCount);
Comments