Thursday, February 9, 2023
HomeProgrammingJava 8 - Acquire and Shuffle Record or Stream

Java 8 – Acquire and Shuffle Record or Stream


On this brief Byte – we’ll check out how one can accumulate and shuffle a listing in Java, utilizing the Practical API, and paired with the collectingAndThen() collector.

Recommendation: If you would like to learn extra about collectingAndThen() – learn our in-depth “Information to Java 8 Collectors: collectingAndThen()”!

Acquire and Shuffle a Record in Java

When accumulating a stream again into a listing (streamed from a Java Assortment) – you could determine to shuffle it. Utilizing Java 8’s Practical API – working with streams is environment friendly and easy.

An intuitive technique to utilize right here is collectingAndThen() which lets you accumulate() a Stream after which run an nameless perform on the consequence:

public class Shuffle {
    personal closing Stream<?> stream;
    
    public Record<?> getList() {
        return stream.accumulate(
            collectingAndThen(
                toList(),
                l -> {
                    Collections.shuffle(l);
                    return l;
                }
            )
        );
    }    
}

Right here, we have collected the stream right into a Record, which is a terminal operation (ending the stream). Then, that record is streamed once more, using the central Collections.shuffle() technique, which accepts any legitimate Assortment and shuffles it in-place.

You may check the strategy and assert the right output with:

@Check
public void shouldShuffleList() {
    Shuffle shuffle = new Shuffle(Stream.of(1,2,3));
    Record<?> record = shuffle.getList();
    
    assertNotEquals("[1, 2, 3]", record.toString());
}

Conclusion

On this brief Byte – we took a take a look at how one can accumulate and shuffle a listing or stream in Java 8+.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments