0

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?

2
  • 4
    What have you tried so far? Please post your code. Commented Sep 18, 2019 at 17:39
  • Iterate through list and when its match print it. Commented Sep 18, 2019 at 17:45

3 Answers 3

2
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));
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This answer works quicker than mine, but a little bit less readable on a bigger scale.
2

.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

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.
string can be a first name or last name.
1

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.