The number of functions from a set XX to another set YY is given by |Y||X||Y||X| since each element in the set XX has |Y||Y| choices.
Hence, in the first case, you have a total of 2n2n functions. To count the number of onto(surjective) functions, the easier way in this case is to subtract out the number of functions which are not onto. In this case, there are only two functions which are not unto, namely the function which maps every element to 11 and the other function which maps every element to 22. Hence, the total number of onto functions is 2n−22n−2.
In the second case, the total number of functions is n2n2. To count the number of one-to-one(injective) functions, all we need is 11 and 22 must map to distinct elements. If the function is one-to-one, then the number of choices for 11 is nn. Once we know where 11 has been mapped to the number of choices for 22, so that the function is one-to-one, is n−1n−1. Hence, the total number of injective functions is n(n−1)n(n−1).