How to undo a word using java using hasprevious () method?

      ArrayList<String> aList = new ArrayList<String>();

        //Add elements to ArrayList object
        aList.add("1");
      aList.add("2");
       aList.add("3");
        aList.add("4");
        aList.add("5");

        //Get an object of ListIterator using listIterator() method
        ListIterator listIterator = aList.listIterator();

        //Traverse in forward direction  
        System.out.println("Traversing ArrayList in forward directio using ListIterator");
        while(listIterator.hasNext())
          System.out.println(listIterator.next());

        /*
          Traverse the ArrayList in reverse direction using hasPrevious and previous
          methods of ListIterator. hasPrevious method returns true if
          ListIterator has more elements to traverse in reverse direction.
          Previous method returns previous element in the list.
        */
        System.out.println("Traversing ArrayList in reverse direction using ListIterator");
        while(listIterator.hasPrevious())
          System.out.println(listIterator.previous());

      }
    }

In the above code, the list of array values ​​is printed in reverse order. But I need to cancel the offer of a single array using the same method. Example: aList.add ("hello world"); there is only one line. but you need to cancel the word as "peace hello."

+4
source share
1 answer

You can split Stringinto an array String(s), convert it to List<String>c Arrays.asList, and then reversethat. Sort of,

String str = "hello world";
List<String> al = Arrays.asList(str.split("\\s+"));
Collections.reverse(al);
for (String s : al) {
    System.out.print(s + " ");
}
System.out.println();

Exit (on request)

world hello 

Alternatively , change yours ListIterator(and you shouldn't use raw types ). Sort of,

String str = "hello world";
List<String> al = Arrays.asList(str.split("\\s+"));
ListIterator<String> listIterator = al.listIterator();

And I get

Traversing ArrayList in forward directio using ListIterator
hello
world
Traversing ArrayList in reverse direction using ListIterator
world
hello
+4

Source: https://habr.com/ru/post/1620489/


All Articles