Know roughly what you can do with stream. I'm not scared to see it for the time being. I try to call it somehow.
//For example, make a list like this
List<String> list = new ArrayList<String>();
list.add("sample");
list.add("sample1");
list.add("sample2");
list.add("sample3");
list.add("sample4");
list.add("sample5");
list
.stream() //Start processing the target collection
.filter(s -> s.length() == 6) //Intermediate operation (processing)
.forEach(s -> System.out.println(s)); //Termination operation (last processing)
//Output only sample
In this way, using the stream () method of collection, perform some intermediate operations and finally perform the termination operation to form it.
stream () is used in List, but Stream exists as an interface just because List has a method. So
Stream<String> st = list.stream();
st.forEach(s -> System.out.println(s));
You can also do something like.
forEach Note that it is a void method
list.stream().forEach(s -> sampleClass.stringList.add(s));
sampleClass.stringList.stream().forEach(s -> System.out.println(s));
collect Use collect () because List is not returned even if you play with stream ()
List<String>editList = list.stream().filter(s -> s.length() == 6).collect(Collectors.toList());
editList.stream().forEach(s -> System.out.println(s));
There are other operations such as count () that returns the number of elements
After that, just insert various intermediate operations List items that are likely to be used frequently
.stream()
.distinct() //Duplicate deletion
.filter(s -> !s.isEmpty()) // isEmpty()Not only leave
.sorted() //Simply ascending
.sorted(Comparator.reverseOrder()) //Simply descending
.map(changeToLength) //Use the created Function
.forEach(s -> System.out.println(s));
The created Function is as follows
//Create a Function called changeToLength with String as an argument and Integer as a return value
//For String s{}Perform the processing inside.
Function<String, Integer> changeToLength= (String s) -> {
return s.length();
};
Recommended Posts