Dieses kleine Programm zeigt wie man die Streams in Java8+ nutzen kann. Man kann mithilfe von Lambda Expressions Elemente aus Collections filtern, reduzieren und verändern. Nützlich um mehrere Funktionen zu meiden, das spart etliche Zeilen code.
This application is a short showcase how Streams in Java8+ works. You can filter, reduce and map elements with the help of lambda expressions from Collections. This is useful to avoid multiple functions.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
public class JavaStream {
public JavaStream(){
List<Integer> origin = new ArrayList<>(randomlistCreator());
streamprocess(origin);
}
private List<Integer> randomlistCreator(){
List<Integer> randomlist = new ArrayList<>();
Random rn = new Random();
rn.setSeed(System.currentTimeMillis());
for(var n = 0; n < 50; n++){
Integer i = rn.nextInt() % 210;
randomlist.add(i);
}
return randomlist;
}
private void streamprocess(List<Integer> origin){
origin
.stream()
.filter(elem -> elem % 2 == 0 && elem > 0)
.map(elem -> (int) elem / 2)
.collect(Collectors.toSet())
.forEach(System.out::println);
}
public static void main(String[] args){
new JavaStream();
}
}