Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
How do I convert java.sql.Array to List<MyCustomEnum>?

I have rs.getArray("lang"); which is java.sql.Array and the lang field is character varying[]. I want to convert it to List<MyEnumLanguage>. As an example I have {fr_FR,en_US} and I have used the following code to convert that my IDE didn't show any errors

List<MyEnumLanguage> myEnumLanguageList = (List<MyEnumLanguage>) rs.getArray("lang");

but it throws an exception org.postgresql.jdbc.PgArray cannot be cast to java.util.List.

My MyEnumLanguage is like:

public enum MyEnumLanguage {
    en_US {
        public String getCode() { return "en_US" }
    },
    de_DE {
        public String getCode() { return "de_DE" }
    };

    private MyEnumLanguage() {
    }
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You cannot cast an array to List. Your IDE does not show any arror because casting happens on runtime.

Instead, you should use Arrays.asList(array) method, which returns a list containing all the elements of the array. Note that if you want to map the elements of the array to another type, you could easily do that with streams. Example:

List<MyEnumLanguage> myEnumLanguageList = Arrays.asList(rs.getArray("lang"))
                .stream()
                .map(arrayElement -> convertToMyEnumLanguage(arrayElement))
                .collect(Collectors.toList());

where convertToMyEnumLanguage() takes an element of your array and returns the corresponding MyEnumLanguage.

Take a look at this post: https://stackify.com/streams-guide-java-8/

UPDATE

Initially I missread the question. You have to first convert your PgArray to a normal java array, before you can use it in Arrays.asList().

This can be done using PgArray.getArray() method, and then cast the returned object to an array of the pgArray's containing type.

UPDATE 2

Improved example:

First of all you should define your enum like this:

public enum MyEnumLanguage {

    en_US("en_US"),
    de_DE("de_DE");

    private final String code;

    private MyEnumLanguage(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public static MyEnumLanguage getEnumByCode(String code) {
        if(code == null || code.isEmpty()) {
            return null;
        }
        for(MyEnumLanguage e : values()) {
            if(e.getCode().equals(code)) {
                return e;
            }
        }

        return null;
    }
}

Then to map your pgArray to a List:

Array pgArray = rs.getArray("lang");
String[] langJavaArray = (String[]) pgArray.getArray(); //this returns an Object, so we cast it to a String array

List<MyEnumLanguage> myEnumLanguageList =
        Arrays.stream(langJavaArray)
        .map(MyEnumLanguage::getEnumByCode)
        .collect(Collectors.toList())
;

Please note that the mapping function does not check for nulls. So if a wrong codes are passed, your list will contain nulls. If this is not the desired result, you have to perform the appropriate checks and handle null cases in your map function.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda