Přidat otázku mezi oblíbenéZasílat nové odpovědi e-mailemVyřešeno Java - ArrayList - Stream - Vypsání názvu a hodnoty fieldu - problém s null

Dobrý den,

Jedná se o poslední úpravu kódu, chtěl jsem to dodělat do konce.

public ArrayList<String> getAllFields() {
        return Arrays.stream(getClass().getDeclaredFields())
                .filter(field -> !Modifier.isStatic(field.getModifiers()))
                .map(this::getFieldValue)
                .filter(field -> !field.isEmpty())
                .collect(Collectors.toCollection(ArrayList::new));
    }

    private String getFieldValue(final Field field) {
        try {
            if (field.get(this) == null) {
                return "";
            }
            String value = field.get(this).toString();
            if (value.matches("-?\\d+")) {
                return field.getName() + " " + value;
            } else if (isName(value)) {
                return value;
            } else {
                return "";
            }
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean isName(String field) {
        return field.equals(name);
    }

Tenhle kód sice dělá přesně, co chci - vypíše jeden String bez názvu fieldu a celá čísla s názvem fieldu, ale metoda getFieldValue je zbytečně složitá.

Na začátku musím vždy zkontrolovat, jestli je field null, jinak to zhavaruje.

Nejde to, prosím Vás, nějak zjednodušit?

Děkuji

loading...
Jsou zobrazeny jen nové odpovědi. Zobrazit všechny
Předmět Autor Datum
Konečný kód je public ArrayList<Text> getAllFields() { return Arrays.stream(getClass().getDeclared… poslední
MichalDM 12.06.2019 23:12
MichalDM

Konečný kód je

    public ArrayList<Text> getAllFields() {
        return Arrays.stream(getClass().getDeclaredFields())
                .filter(field -> !Modifier.isStatic(field.getModifiers()))
                .map(this::getFieldValue)
                .filter(field -> !field.isEmpty())
                .map(field -> new Text(field))
                .collect(Collectors.toCollection(ArrayList::new));
    }

    private String getFieldValue(final Field field) {
        try {
            if (field.get(this) == null) {
                return "";
            }
            String value = field.get(this).toString();
            if (value.matches("-?\\d+")) {
                return field.getName() + " " + value;
            } else if (value.equals(NAME)) {
                return value;
            } else {
                return "";
            }
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

S null to nijak nepůjde, NAME je field objektu a pro vypsání pod sebou, je nejlepší použít javafx.scene.layout.VBox. Ten však String nevezme. Proto je nutné to přetypovat na javafx.scene.text.Text.

Zpět do poradny Odpovědět na původní otázku Nahoru

loading...