I am looking for a way in java to sort a list of strings based on user input in Java. for example, my list contains ["Pat Henderson", "Zach Harrington", "Pat Douglas", "Karen Walsh"]
, if a user enters the first name "Pat"
how would I be able to print out only the Pats in the list and same for surnames?
ArrayList<String> str = new ArrayList<String>();
for(int i = 0 ; i < str.size() ; i++) {
if(str.get(i).contains("your_user_input")) {
System.out.println(str.get(i));
}
}
.filter()
introduced in Java 8 would to the thing.
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList("Pat Henderson", "Zach Harrington", "Pat Douglas", "Karen Walsh"));
String startsWith = "Pat";
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith(startsWith))
.collect(Collectors.toList());
A little remark. Sorting is when you rearrange the position of the elements without removing any.
Supposing that each element of the list have a name and a last name separated by a whitespace or more, with Java 8 you could filter on the name or the last name in this way :
List<String> list = Arrays.asList("Pat Henderson", "Zach Harrington", "Pat Douglas", "Karen Walsh");
String nameOrLastNameToFilter = ...;
list.stream().filter(s -> Arrays.stream(s.split("\\s+"))
.anyMatch(n->n.equals(nameOrLastNameToFilter))
)
.collect(toList());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.