javalambdamapping

How to implement a reverse mapping Java using lambdas?


As far as I know, in Java 8, mapping works as follows

enter image description here

for example:

List<String> objList = Arrays.asList("1", "2", "3", "4", "5", "6", "7");
 objList.stream().map( i -> i ). forEach( i -> System.out.print(" " + i));

output:

1 2 3 4 5 6 7

but my question is: how I can do the reverse mapping? like

enter image description here

so output will be this

 7 6 5 4 3 2 1 

Or it is not possible to do so?


Solution

  • In this example I accumulate the list into a LinkedList.

    The LinkedList implements Deque (Double ended queue) which allows me to append the items in a last-in-first-out (LIFO) order.

    I perform the accumulation in the collect method using LinkedList::addFirst which places the items read off the stream at the head of the list.

    public static void main(final String... args) {
    
        final List<String> objList = Arrays.asList("1", "2", "3", "4", "5", "6", "7");
    
    
        final List<String> reversed = objList.stream()
            .collect(LinkedList::new, LinkedList::addFirst, LinkedList::addAll);
    
        //[7, 6, 5, 4, 3, 2, 1]  
        System.out.println(reversed);
    
    }
    

    The solution below is OK but I don't like having to close over the original list.

    public static void main(final String... args) {
    
        final List<String> objList = Arrays.asList("1", "2", "3", "4", "5", "6", "7");
    
         final List<String> reversed = IntStream.range(-(objList.size() - 1), 1)
            .mapToObj(i -> objList.get(-i))
            .collect(Collectors.toList());
    
        //[7, 6, 5, 4, 3, 2, 1]  
        System.out.println(reversed);
    
    }