mapはFunction
mapToIntはToIntFunction
ToIntFunctionはreturn int
package sampleproject;
import java.util.List;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.stream.IntStream;
import java.util.stream.Stream;
class Item {
int i;
Item(int i){
this.i = i;
}
int getI() {
return this.i;
}
}
public class SampleProject {
public static void main(String[] args) {
List<Integer> l = List.of(1,2,3,4,5);
List<String> l2 = List.of("1","2","3","4","5");
int[][] array = {{1,2},{3,4},{5,6}};
Function<Integer,String> f = a -> String.valueOf(a) + "xxx";
l.stream().<String>map(f).forEach(System.out::println);
ToIntFunction<String> tf = s -> Integer.valueOf(s);
List<Item> l3 = List.of(
new Item(1),
new Item(2),
new Item(3),
new Item(4),
new Item(5)
);
l2.stream().mapToInt(tf).forEach(System.out::println);
Stream<int[]> st = Stream.of(array);
st.flatMapToInt(x -> IntStream.of(x)).forEach(System.out::println);
System.out.println(l2.stream().mapToInt(tf).average().getAsDouble());
l3.stream().mapToInt(Item::getI).average().getAsDouble();
}
}
1xxx
2xxx
3xxx
4xxx
5xxx
1
2
3
4
5
1
2
3
4
5
6
3.0