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?
-
4What have you tried so far? Please post your code.Jacob G.– Jacob G.2019-09-18 17:39:36 +00:00Commented Sep 18, 2019 at 17:39
-
Iterate through list and when its match print it.SSP– SSP2019-09-18 17:45:35 +00:00Commented Sep 18, 2019 at 17:45
Add a comment
|
3 Answers
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));
}
}
1 Comment
Ilya Sereb
This answer works quicker than mine, but a little bit less readable on a bigger scale.
.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.
2 Comments
Charlie Ansell
Thank you for your answer. I am asked as a requirement to sort by first name or by last name so I assumed what the requirement was asking was to show only the names that match the string entered by the user.
SSP
string can be a first name or last name.
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());