Last active
April 14, 2020 11:31
-
-
Save lizettepreiss/5d80e2b765612952956e1c36e38221bb to your computer and use it in GitHub Desktop.
Java Generics Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package java_examples; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class GenericExample { | |
/** | |
* | |
* @param args | |
*/ | |
public static void main(String[] args){ | |
List<Integer> aLst = new ArrayList<>(); | |
aLst.add(1); | |
aLst.add(2); | |
/* Now invoke the genericMethod with an ArrayList of Integers as an argument*/ | |
List<Integer> aList = genericMethod(aLst); | |
aList.forEach(elem -> System.out.println(elem)); | |
aList.forEach(System.out::println); | |
List<String> bLst = new ArrayList<>(); | |
bLst.add("a"); | |
bLst.add("s"); | |
/* Now invoke the genericMethod with an ArrayList of Strings as an argument*/ | |
List<String> bList = genericMethod(bLst); | |
bList.forEach(elem -> System.out.println(elem)); | |
bList.forEach(System.out::println); | |
} | |
/** | |
* | |
* @param list | |
* @return List | |
*/ | |
public static <T> List<T> genericMethod(List<T> list) { | |
return list.stream().collect(Collectors.toList()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment