-3

This is what I've been trying:

public class Assignement2_java8 {

    public static void main(String[] args) {
        ArrayList<String> al = new ArrayList<String>();
        al.add("infosys");
        al.add("wipro");
        al.add("tcs");
        al.add("amazon");
        al.add("microsoft");
        al.add("google");
        al.add("acctenture");
        al.add("hcl");
        al.add("flipkart");
        al.add("apple");

        al.forEach(n -> System.out.println(n.reverse()));
    }
}

I know I can use an array of words then store it in ArrayList but I want to know why I can't use this.

Ivo Mori
  • 2,177
  • 5
  • 24
  • 35
  • The `reverse` method cannot be resolved on `n` because `n` is of type `String`, and `String` doesn't have such a method. – Ivo Mori Jul 24 '20 at 01:20
  • If you do a little research here on Stack Overflow you'll find [Reverse a string in Java](https://stackoverflow.com/q/7569335/5698098) showing you how to reverse a string. This is then what you need to use for each `n`. – Ivo Mori Jul 24 '20 at 01:29
  • Please clarify what you want to accomplish (giving a specific expected output example). Do you want to reverse the order of your list items (e.g. "infosys", ..., "apple" => "infosys", ..., "apple") or do you want to reverse each String element (e.g. "infosys", ..., "apple" => "sysofni", ..., "elppa")? – Ivo Mori Jul 24 '20 at 01:43

1 Answers1

0

Add 10 names to array list and print them in reverse order using lamda expression.

ArrayList does not have a reverse method. Create your own Consumer that takes a List as an argument.

Consumer<List<String>> reversePrint = lst-> {
    for (int i = lst.size()-1; i >= 0; i--) {
         System.out.println(lst.get(i));
    }
};
            
reversePrint.accept(al);

Prints

apple
flipkart
hcl
acctenture
google
microsoft
amazon
tcs
wipro
infosys

If you want to print each string in reverse (which is different than what your title says), then you can do it like this.

al.forEach(n -> System.out.println(new StringBuilder(n).reverse()));

Prints

sysofni
orpiw
sct
nozama
tfosorcim
elgoog
erutnetcca
lch
trakpilf
elppa
Ivo Mori
  • 2,177
  • 5
  • 24
  • 35
WJS
  • 36,363
  • 4
  • 24
  • 39