You can use Collectors#toMap
and pass any function for the value e.g. by using a UnaryOperator as shown below:
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
UnaryOperator<Integer> add = x -> x + 5;
UnaryOperator<Integer> mutiply = x -> x * 5;
UnaryOperator<Integer> factorial = x -> factorial(x);
// Test
List<Integer> list = List.of(1, 2, 3, 4, 5);
Map<Integer, Integer> map1 = list.stream().collect(Collectors.toMap(Function.identity(), add));
Map<Integer, Integer> map2 = list.stream().collect(Collectors.toMap(Function.identity(), mutiply));
Map<Integer, Integer> map3 = list.stream().collect(Collectors.toMap(Function.identity(), factorial));
System.out.println(map1);
System.out.println(map2);
System.out.println(map3);
}
static int getValue(int x, UnaryOperator<Integer> function) {
return function.apply(x);
}
static int factorial(int x) {
if (x <= 0) {
return 1;
}
return x * factorial(x - 1);
}
}
Output:
{1=6, 2=7, 3=8, 4=9, 5=10}
{1=5, 2=10, 3=15, 4=20, 5=25}
{1=1, 2=2, 3=6, 4=24, 5=120}