title: Make a generic function in Java
body: <p>I have two methods to get data from the database. They differ only in the request and the return type. Is it possible to combine them somehow so that the code does not repeat itself?</p>
  <pre><code>public ObservableList&lt;Car&gt; getAllCars() {
      ObservableList&lt;Car&gt; list = FXCollections.observableArrayList();
      Connection connection = MyConnection.connection;
      String query = &quot;SELECT * FROM cars&quot;;
      try {
          Statement statement = connection.createStatement();
          ResultSet rs = statement.executeQuery(query);
          while (rs.next()) {
              Car car = new Car(rs.getInt(&quot;ID&quot;), rs.getInt(&quot;STYLE_ID&quot;),
                      rs.getString(&quot;MAKE&quot;), rs.getString(&quot;MODEL&quot;),
                      rs.getInt(&quot;YEAR&quot;), rs.getInt(&quot;PRICE&quot;));
              list.add(car);
          }
      } catch (Exception ex) {
          ex.printStackTrace();
      }
      return list;
  }
  
  public ObservableList&lt;Style&gt; getAllStyles() {
      ObservableList&lt;Style&gt; list = FXCollections.observableArrayList();
      Connection connection = MyConnection.connection;
      String query = &quot;SELECT * FROM styles&quot;;
      try {
          Statement statement = connection.createStatement();
          ResultSet rs = statement.executeQuery(query);
          while (rs.next()) {
              Style style = new Style(rs.getInt(&quot;ID&quot;), rs.getString(&quot;NAME&quot;));
              list.add(style);
          }
      } catch (Exception ex) {
          ex.printStackTrace();
      }
      return list;
  }
  </code></pre>