Mehrose
Mehrose

Reputation: 87

Filter the Big String

I have an array of String and the task is to find out the longest string in the array and the location of that string.I am wondering if I can convert the array to list and by using stream I can solve the same problem. Any help would be appreciated

I've already solved the problem using traditional way, using loops and some if conditions

String names[]={"John","Malisa","Stack Overflow"};

String b=names[i];
int max=b.length();

for(int i=1;i<names.length;i++) {
    if(max<names[i].length) {
        max=names[i].length;
        b=names[i];
    }
}

Upvotes: 0

Views: 538

Answers (4)

Samuel Philipp
Samuel Philipp

Reputation: 11042

Here is another approach for getting the longest string and its index at the same time:

String[] names = {"John", "Malisa", "Stack Overflow"};
Optional<Map.Entry<String, Integer>> result = IntStream.range(0, names.length).boxed()
        .collect(Collectors.toMap(i -> names[i], Function.identity()))
        .entrySet().stream()
        .max(Comparator.comparing(e -> e.getKey().length()));

result.ifPresent(e -> System.out.println("Longest String: '" + e.getKey() + "' at index " + e.getValue()));

This creates a map with the string and its index. After that it returns the entry with the longest string.

The result for your names array is:

Longest String: 'Stack Overflow' at index 2

Upvotes: 0

Egor
Egor

Reputation: 1409

Your can use Arrays.stream and compare length:

    String names[]={"John","Malisa","Stack Overflow"};
    Optional<String> max = Arrays.stream(names)
            .max(Comparator.comparingInt(String::length));
    System.out.println(max.orElse("none"));

UPD I didn't understand your question correctly. You can use this code to get index of max element:

    String names[]={"John","Malisa","Stack Overflow"};

    int index = IntStream.range(0, names.length)
            .reduce((i, j) -> names[i].length() > names[j].length() ? i : j)
            .getAsInt();

    System.out.println(index);

Upvotes: 0

Ruslan
Ruslan

Reputation: 6290

You don't need filter method to find the longest string in array. Use max with comparator:

String max = Arrays.stream(names)
        .max(Comparator.comparingInt(String::length))
        .orElse("");

To find the index of this element use:

int index = Arrays.asList(names).indexOf(max);

Upvotes: 3

Jaspreet Jolly
Jaspreet Jolly

Reputation: 1313

Simply use :-

Arrays.stream(names)
       .sorted(Comparator.comparing(String::length,Comparator.reverseOrder()))
       .findFirst()
       .get()

Upvotes: 0

Related Questions