0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

stream().map(), stream().mapToInt()

Last updated at Posted at 2023-03-01

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?