Lucas_Camara 17 de out. de 2021 1 like
Isso?
import java.util.ArrayList ;
import java.util.List ;
public class Main {
public static void main ( String [] args ) throws Exception {
List < Integer > teste1 = obterListaDeObjetosBaseadoNaString ( Integer . class , "1" , "2" , "3" );
List < Double > teste2 = obterListaDeObjetosBaseadoNaString ( Double . class , "1" , "2" , "3" );
List < Custom > teste3 = obterListaDeObjetosBaseadoNaString ( Custom . class , "1" , "2" , "3" );
}
public static < T > List < T > obterListaDeObjetosBaseadoNaString ( Class < T > classe , String ... linhas ) {
return new ArrayList < T > ();
}
static class Custom {
}
}
A “mágica” acontece por conta do <T> definido no método.
Leia mais sobre aqui: https://docs.oracle.com/javase/tutorial/java/generics/methods.html
luismiguel 17 de out. de 2021
Cara, não peguei muito bem a ideia. Até deu certo aqui, mas ainda continuo com o mesmo código só que agora com um cast no próprio método.
public static < T > List < T > obterListaDeObjetosBaseadoNaString ( Class < T > classe , String ... linhas ) {
List < String > nomes = new ArrayList <> ();
for ( String linha : linhas ) {
if ( linha . contains ( "," )) {
String [] elementosDaLinhaSeparadaPorVirgula = linha . split ( "," );
for ( String nome : elementosDaLinhaSeparadaPorVirgula ) {
nomes . add ( nome );
}
} else {
nomes . add ( linha );
}
}
if ( classe == Diretor . class ) {
return ( List < T > ) nomes . stream ()
. map ( Diretor :: new )
. collect ( Collectors . toList ());
} else {
return ( List < T > ) nomes . stream ()
. map ( Genero :: new )
. collect ( Collectors . toList ());
}
}
Solucao aceita
Lucas_Camara 17 de out. de 2021 2 likes
Para evitar esses casts (e tb vários IF-ELSE ), vc pode usar expressões lambda:
public static void main ( String [] args ) {
List < Diretor > diretores = obterListaDeObjetosBaseadoNaString ( Diretor :: new , "1" , "2" , "3" );
List < Genero > generos = obterListaDeObjetosBaseadoNaString ( Genero :: new , "1" , "2" , "3" );
}
public static < T > List < T > obterListaDeObjetosBaseadoNaString ( Function < String , T > fn , String ... linhas ) {
List < String > nomes = new ArrayList <> ();
for ( String linha : linhas ) {
if ( linha . contains ( "," )) {
String [] elementosDaLinhaSeparadaPorVirgula = linha . split ( "," );
for ( String nome : elementosDaLinhaSeparadaPorVirgula ) {
nomes . add ( nome );
}
} else {
nomes . add ( linha );
}
}
return nomes . stream (). map ( fn ). collect ( Collectors . toList ());
}
Em vez de usar a expressão com ::new , poderia ser assim também:
List < Diretor > diretores = obterListaDeObjetosBaseadoNaString (( v ) -> new Diretor ( v ), "1" , "2" , "3" );
List < Genero > generos = obterListaDeObjetosBaseadoNaString (( v ) -> new Genero ( v ), "1" , "2" , "3" );
luismiguel 17 de out. de 2021
Utilizando interface funcional ficou mais simples de entender o que está sendo feito. Obrigado pela ajuda.