How efficiently we can get the required output from the list in java?

ash das :
CircuitID   Department  Hours

--------------------------------

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70

Now i have to create one list which will have records on following criteria:

  1. In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {



     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {



      if (circuitList().get(i).getDepartment().equals(“Electricity”) {



        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours

Circuit class is having pojo objects with getter setters of this three objects.

 public class Circuit {

        String circuitID;
        int hours;
        String department;
}
Sero :
public static Map<String, Circuit> getMaxHours(final List<Circuit> circuitsList) {
    final Map<String, Circuit> mappedCircuitsById = new HashMap<String, Circuit>();

    for (final Circuit circuit : circuitsList) {
        if (!mappedCircuitsById.containsKey(circuit.getCircuitID())) {
            mappedCircuitsById.put(circuit.getCircuitID(), circuit);
        } else {
            final Circuit existingMax = mappedCircuitsById.get(circuit.getCircuitID());
            if (circuit.getHours() > existingMax.getHours()) mappedCircuitsById.put(circuit.getCircuitID(), circuit);
            else if (circuit.getHours() == existingMax.getHours()) {
                if (circuit.getDepartment().equals("Electricity")) mappedCircuitsById.put(circuit.getCircuitID(), circuit);
                else if (existingMax.getDepartment().equals("Electricity")) mappedCircuitsById.put(circuit.getCircuitID(), existingMax);
            }
        }
    }

    return mappedCircuitsById;
}

Create a map where the key of the map is the circuitID and the value is the Circuit object which meets the "max hours" requirements. Iterate over the elements of the list and and update the map accordingly to store the new "max hours" Circuit object

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86114&siteId=1