将对象列表转换为字符串列表



我正在使用Spring数据jpafindAll()方法。它返回对象列表。这是实体。

@Entity
@Table(name = "country")
@Data
public class CountryEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "country_id")
private Long id;
@Column(name = "country_name")
private String name;
@OneToMany(mappedBy ="countryEntity")
private Collection<GovernmentEntity> governments;
}

和数据jpa的findAll()方法是

List<CountryEntity> entities = countryRepo.findAll();

我想获得国家名称的字符串列表不使用循环或流(性能问题)。

我使用流,它工作良好与javaFx ListView

@FxmlView("/address.fxml")
@Component
@RequiredArgsConstructor
public class HomeController implements Initializable {
private ObservableList<String> countriesNames;
@FXML
private ListView<String> countryListView;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
List<CountryEntity> entities = countryRepo.findAll();
List <String> countryList = entities.stream().map(o-> Objects.toString(o.getName())).collect(Collectors.toList());
countriesNames = FXCollections.observableList(countryList);
countryListView.getItems().addAll(countriesNames);
}
}

使ListViewListView<CountryEntity>,并使用单元格工厂自定义显示:

public class HomeController implements Initializable {
private ObservableList<String> countriesNames;
@FXML
private ListView<CountryEntity> countryListView;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
List<CountryEntity> entities = countryRepo.findAll();
countryListView.getItems().addAll(entities);
countryListView.setCellFactory(lv -> new ListCell<CountryEntity>() {
@Override
protected void updateItem(CountryEntity country, boolean empty) {
super.updateItem(country, empty);
if (empty || country == null) {
setText("");
} else {
setText(country.getName()); // or however you want to display it
}
}); 
}
}

如果您真的只想要一个国家名称列表,并且不想检索CountryEntity列表并从中提取名称,那么您需要为此目的在存储库中定义一个方法:

public interface CountryEntityRepository extends JpaRepository<CountryEntity, Long> {
// existing methods...
@Query("select c.name from CountryEntity c")
List<String> findCountryNames() ;
}

然后当然是

@FXML
private ListView<String> countryListView ;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
countryListView.getItems().addAll(countryRepo.findCountryNames());
}

然而,第一种方法几乎肯定是首选的。在某些时候,您可能需要CountryEntity中的其他数据。

最新更新