There are following way to group a string based on their length.
- Here we are making List type three group equalsGroup, lessThanGroup and greaterThanGroup..
- Inside groupStringsByLength(List<String> input) method, first we iterate the list.
- we assume make a group of String which number of character is 5.
- Now validate if String length is less than 5 then add this String to lessThanGroup List group.
- else if String length is equals to 5 then add this String to equalsGroup List group.
- else if String length is greater than 5 then add this String to greaterThanGroup List group.
- Print the all list group.
import java.util.ArrayList;
import java.util.List;
public class GroupStringByLength {
static List<String> lessThanGroup = new ArrayList<String>();
static List<String> equalsGroup = new ArrayList<String>();
static List<String> greaterThanGroup = new ArrayList<String>();
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Java");
list.add("hello");
list.add("Spring Boot");
list.add("Jsp");
list.add("Hibernate");
list.add("Maven");
groupStringsByLength(list);
System.out.println("Less Than Group Data :- " + lessThanGroup);
System.out.println("Equals Group Data :- " + equalsGroup);
System.out.println("Greater Than Group Data :- " + greaterThanGroup);
}
public static void groupStringsByLength(List<String> input) {
for (String str : input) {
if (str.length() < 5) {
lessThanGroup.add(str);
} else if (str.length() == 5) {
equalsGroup.add(str);
} else if (str.length() > 5) {
greaterThanGroup.add(str);
}
}
}
}
Output :-
Less Than Group Data :- [Java, Jsp]
Equals Group Data :- [hello, Maven]
Greater Than Group Data :- [Spring Boot, Hibernate]