Java Code Examples for java.util.Collections.max()

The following are Jave code examples for showing how to use max() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: javaide   File: FindMaximumOfArrayListExample.java   View Source Code Vote up 6 votes
public static void main(String[] args) {

    //create an ArrayList object
    ArrayList arrayList = new ArrayList();

    //Add elements to Arraylist
    arrayList.add(new Integer("327482"));
    arrayList.add(new Integer("13408"));
    arrayList.add(new Integer("802348"));
    arrayList.add(new Integer("345308"));
    arrayList.add(new Integer("509324"));

    /*
       To find maximum element of Java ArrayList use,
       static Object max(Collection c) method of Collections class.

       This method returns the maximum element of Java ArrayList according to
       its natural ordering.
    */

    Object obj = Collections.max(arrayList);

    System.out.println("Maximum Element of Java ArrayList is : " + obj);
  }
 
Example 2
Project: oma-riista-android   File: GameCalendar.java   View Source Code Vote up 6 votes
/**
 * Sets data for calendar months
 *
 * @param calendarData array of data containing values from January to December
 */
public void setData(ArrayList<Integer> calendarData) {
    mCalendarData = calendarData;

    int currentMonth = mStartMonth;
    int monthOrdinal = 0;
    int maxLevel = Collections.max(calendarData);
    while (monthOrdinal < 12 && monthOrdinal < mCalendarMonthViews.size()) {
        CalendarMonth calendarMonth = mCalendarMonthViews.get(monthOrdinal);
        if (mCalendarData.size() > currentMonth) {
            calendarMonth.setMonth(currentMonth, mCalendarData.get(currentMonth), maxLevel);
        } else {
            calendarMonth.setMonth(currentMonth, 0, 0);
        }
        currentMonth++;
        if (currentMonth == 12) {
            currentMonth = 0;
        }
        monthOrdinal++;
    }
    mCalendarData = calendarData;
}
 
Example 3
Project: TensorFlowOnYARN   File: ClusterSpec.java   View Source Code Vote up 6 votes
public Map<String, List<String>> as_dict() {
  Map<String, List<String>> job_tasks_map = new HashMap<String, List<String>>();
  String job_name;
  List<String> jobs = this.jobs();
  for (int i = 0; i < jobs.size(); i++) {
    job_name = jobs.get(i);
    List<Integer> task_indices = this.task_indices(job_name);
    if (Collections.max(task_indices) + 1 == task_indices.size()) //the tasks indices are dense
    {
      job_tasks_map.put(job_name, this.job_tasks(job_name));
    } else //the tasks indices are not dense, manually make the list dense
    {
      List<String> tasks = new ArrayList<String>();
      Integer task_index;
      for (int j = 0; j < task_indices.size(); j++) {
        task_index = task_indices.get(j);
        tasks.add(this.task_address(job_name, task_index));

      }
    }
  }
  return job_tasks_map;
}
 
Example 4
Project: PlusGram   File: CameraController.java   View Source Code Vote up 6 votes
public static Size chooseOptimalSize(List<Size> choices, int width, int height, Size aspectRatio) {
    List<Size> bigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (int a = 0; a < choices.size(); a++) {
        Size option = choices.get(a);
        if (option.getHeight() == option.getWidth() * h / w && option.getWidth() >= width && option.getHeight() >= height) {
            bigEnough.add(option);
        }
    }
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else {
        return Collections.max(choices, new CompareSizesByArea());
    }
}
 
Example 5
Project: featurea   File: Rectangle.java   View Source Code Vote up 5 votes
public double right() {
    if (isTile()) {
        return x2;
    } else {
        return Collections.max(Arrays.asList(x1, x2, x3, x4));
    }
}
 
Example 6
Project: elements-of-programming-interviews   File: StackWithMaxTest.java   View Source Code Vote up 5 votes
private void test(int length) {
    List<Integer> values = StreamUtil.sequence(length);
    final Integer max = Collections.max(values);
    assertTracksMax(values);

    IntStream.range(0, N)
            .forEach(n -> {
                Collections.shuffle(values);
                StackWithMax stack = createStack(values);
                Assert.assertEquals(max, stack.max());
            });
}
 
Example 7
Project: TuLiPA-frames   File: TypeHierarchy.java   View Source Code Vote up 5 votes
public String toString() {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i <= Collections.max(tyHi.keySet()); i++) {
        System.out.println("spec: " + i);
        for (Type type : tyHi.get(i)) {
            System.out.println(type.toString());
        }
        System.out.println();
    }
    return sb.toString();
}
 
Example 8
Project: fo-veilarbjobbsokerkompetanse   File: JobbsokerKartleggingDAO.java   View Source Code Vote up 5 votes
public JobbsokerKartlegging hentNyesteJobbsokerKartlegging(String aktorId) {
    List<JobbsokerKartlegging> jobbsokerKartlegginger = hentJobbsokerKartlegginger(aktorId);
    return Collections.max(jobbsokerKartlegginger, new Comparator<JobbsokerKartlegging>() {
        @Override
        public int compare(JobbsokerKartlegging o1, JobbsokerKartlegging o2) {
            return o1.getLagretTidspunkt().compareTo(o2.getLagretTidspunkt());
        }
    });
}
 
Example 9
Project: hadoop   File: TestOfflineImageViewer.java   View Source Code Vote up 5 votes
@Test
public void testFileDistributionCalculator() throws IOException {
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  PrintStream o = new PrintStream(output);
  new FileDistributionCalculator(new Configuration(), 0, 0, o)
      .visit(new RandomAccessFile(originalFsimage, "r"));
  o.close();

  String outputString = output.toString();
  Pattern p = Pattern.compile("totalFiles = (\\d+)\n");
  Matcher matcher = p.matcher(outputString);
  assertTrue(matcher.find() && matcher.groupCount() == 1);
  int totalFiles = Integer.parseInt(matcher.group(1));
  assertEquals(NUM_DIRS * FILES_PER_DIR, totalFiles);

  p = Pattern.compile("totalDirectories = (\\d+)\n");
  matcher = p.matcher(outputString);
  assertTrue(matcher.find() && matcher.groupCount() == 1);
  int totalDirs = Integer.parseInt(matcher.group(1));
  // totalDirs includes root directory
  assertEquals(dirCount + 1, totalDirs);

  FileStatus maxFile = Collections.max(writtenFiles.values(),
      new Comparator<FileStatus>() {
    @Override
    public int compare(FileStatus first, FileStatus second) {
      return first.getLen() < second.getLen() ? -1 :
          ((first.getLen() == second.getLen()) ? 0 : 1);
    }
  });
  p = Pattern.compile("maxFileSize = (\\d+)\n");
  matcher = p.matcher(output.toString("UTF-8"));
  assertTrue(matcher.find() && matcher.groupCount() == 1);
  assertEquals(maxFile.getLen(), Long.parseLong(matcher.group(1)));
}
 
Example 10
Project: Fatigue-Detection   File: CameraEngine.java   View Source Code Vote up 5 votes
private static Camera.Size choosePreferredSize(List<Camera.Size> sizes,double aspectRatio) {
    List<Camera.Size> options = new ArrayList<>();
    for (Camera.Size option : sizes) {
        if(option.width==1280 && option.height==720)
            return option;
        if (Math.abs((int)(option.height * aspectRatio)-option.width)<10) {
            options.add(option);
        }
    }
    if (options.size() > 0) {
        return Collections.max(options, new CompareSizesByArea());
    } else {
        return sizes.get(sizes.size()-1);
    }
}
 
Example 11
Project: Image-Detection-Samples   File: FDCamera2Presenter.java   View Source Code Vote up 5 votes
private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
                                      int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {

    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    // Collect the supported resolutions that are smaller than the preview Surface
    List<Size> notBigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
        if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
                option.getHeight() == option.getWidth() * h / w) {
            if (option.getWidth() >= textureViewWidth &&
                    option.getHeight() >= textureViewHeight) {
                bigEnough.add(option);
            } else {
                notBigEnough.add(option);
            }
        }
    }

    // Pick the smallest of those big enough. If there is no one big enough, pick the
    // largest of those not big enough.
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0) {
        return Collections.max(notBigEnough, new CompareSizesByArea());
    } else {
        Log.e(TAG, "Couldn't find any suitable preview size");
        return choices[0];
    }
}
 
Example 12
Project: openrouteservice   File: GreenIndexGraphStorageBuilder.java   View Source Code Vote up 5 votes
private void prepareGreenIndexSlots() {
    double max = Collections.max(_greenIndices.values());
    double min = Collections.min(_greenIndices.values());
    double step = (max - min) / TOTAL_LEVEL;
    // Divide the range of raw green index values into TOTAL_LEVEL,
    // then map the raw value to [0..TOTAL_LEVEL - 1]
    for (byte i = 0; i < TOTAL_LEVEL; i++) {
        _slots.put(i, new SlotRange(min + i * step, min + (i + 1) * step));
    }
}
 
Example 13
Project: Cam2Caption   File: Camera2BasicFragment.java   View Source Code Vote up 5 votes
/**
 * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
 * is at least as large as the respective texture view size, and that is at most as large as the
 * respective max size, and whose aspect ratio matches with the specified value. If such size
 * doesn't exist, choose the largest one that is at most as large as the respective max size,
 * and whose aspect ratio matches with the specified value.
 *
 * @param choices           The list of sizes that the camera supports for the intended output
 *                          class
 * @param textureViewWidth  The width of the texture view relative to sensor coordinate
 * @param textureViewHeight The height of the texture view relative to sensor coordinate
 * @param maxWidth          The maximum width that can be chosen
 * @param maxHeight         The maximum height that can be chosen
 * @param aspectRatio       The aspect ratio
 * @return The optimal {@code Size}, or an arbitrary one if none were big enough
 */
private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
                                      int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {

    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    // Collect the supported resolutions that are smaller than the preview Surface
    List<Size> notBigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
        if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
                option.getHeight() == option.getWidth() * h / w) {
            if (option.getWidth() >= textureViewWidth &&
                    option.getHeight() >= textureViewHeight) {
                bigEnough.add(option);
            } else {
                notBigEnough.add(option);
            }
        }
    }

    // Pick the smallest of those big enough. If there is no one big enough, pick the
    // largest of those not big enough.
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0) {
        return Collections.max(notBigEnough, new CompareSizesByArea());
    } else {
        Log.e(TAG, "Couldn't find any suitable preview size");
        return choices[0];
    }
}
 
Example 14
Project: Higher-Cloud-Computing-Project   File: CacheUtils.java   View Source Code Vote up 5 votes
/**
 * @param matrixUuid Matrix UUID.
 * @return Maximum value obtained using sparse logic.
 */
@SuppressWarnings("unchecked")
public static <K, V> double sparseMax(UUID matrixUuid, String cacheName) {
    A.notNull(matrixUuid, "matrixUuid");
    A.notNull(cacheName, "cacheName");

    Collection<Double> maxes = fold(cacheName, (CacheEntry<K, V> ce, Double acc) -> {
        V v = ce.entry().getValue();

        double max;

        if (v instanceof Map) {
            Map<Integer, Double> map = (Map<Integer, Double>)v;

            max = Collections.max(map.values());
        }
        else if (v instanceof MatrixBlockEntry) {
            MatrixBlockEntry be = (MatrixBlockEntry)v;

            max = be.maxValue();
        }
        else
            throw new UnsupportedOperationException();

        if (acc == null)
            return max;
        else
            return Math.max(acc, max);

    }, sparseKeyFilter(matrixUuid));

    return Collections.max(maxes);
}
 
Example 15
Project: spring-boot-greendogdelivery-casadocodigo   File: NovoPedidoController.java   View Source Code Vote up 4 votes
@GetMapping("/rest/pedido/novo/{clienteId}/{listaDeItens}")
public RespostaDTO novo(@PathVariable("clienteId") Long clienteId,@PathVariable("listaDeItens") String listaDeItens) {

	RespostaDTO dto = new RespostaDTO();

	try {
		Cliente c = clienteRepository.findOne(clienteId);

		String[] listaDeItensID = listaDeItens.split(",");

		Pedido pedido = new Pedido();

		double valorTotal = 0;
		List<Item> itensPedidos = new ArrayList<Item>();

		for (String itemId : listaDeItensID) {
			Item item = itemRepository.findOne(Long.parseLong(itemId));
			itensPedidos.add(item);
			valorTotal += item.getPreco();
		}
		pedido.setItens(itensPedidos);
		pedido.setValorTotal(valorTotal);
		pedido.setData(new Date());
		pedido.setCliente(c);
		c.getPedidos().add(pedido);

		this.clienteRepository.saveAndFlush(c);
		
		enviaNotificacao.enviaEmail(c,pedido);
		
		List<Long> pedidosID = new ArrayList<Long>();
		for (Pedido p : c.getPedidos()) {
			pedidosID.add(p.getId());
		}

		Long ultimoPedido = Collections.max(pedidosID);

		dto = new RespostaDTO(ultimoPedido,valorTotal,"Pedido efetuado com sucesso");

	} catch (Exception e) {
		dto.setMensagem("Erro: " + e.getMessage());
	}
	return dto;

}
 
Example 16
Project: tac-kbp-eal   File: CorefAnnotation.java   View Source Code Vote up 4 votes
public CorefAnnotation copyMerging(CorefAnnotation toMerge) {
  checkArgument(docId == toMerge.docId());
  // (1) initialize our mapping of CASes to coref indices with the
  // mappings seen in *baseline*. This is used to track the mappings during
  // construction, but ret (below) is used to construct the result
  final Map<KBPString, Integer> newCASToCoref = Maps.newHashMap(CASesToIDs);
  final Builder ret = strictCopyBuilder();

  // the next empty index for adding a new coref cluster
  // this potentially could fail due to overflow, but the chances are tiny and
  // the stakes are low, so we won't worry about it
  int nextIndex = newCASToCoref.isEmpty() ? 1 : (1 + Collections.max(newCASToCoref.values()));

  // (2) gather a map of coref IDs to the CASes in the corresponding cluster
  // from *additional*
  final Multimap<Integer, KBPString> additionalCorefToCAS = toMerge.idToCASes;

  for (final Map.Entry<KBPString, Integer> newCorefRelation : toMerge.CASesToIDs.entrySet()) {
    final int corefId = newCorefRelation.getValue();
    final KBPString CAS = newCorefRelation.getKey();

    if (!newCASToCoref.containsKey(CAS)) {
      // this CAS was not previously coreffed
      final StringBuilder msg = new StringBuilder();

      // use the baseline cluster which contains most  clustermates of CAS
      // in "additional"
      final Collection<KBPString> clusterMates = additionalCorefToCAS.get(
          corefId);
      msg.append("\t\tFor CAS ").append(CAS).append(" no coref ID was found in baseline. It has ")
          .append(clusterMates.size()).append(" clustermates\n");

      // We use an ImmutableMultiset to have deterministic iteration order
      // and therefore deterministic tie-breaking if two clusters tie
      // on clustermate count
      final ImmutableMultiset.Builder<Integer> bCorefIDsOfClusterMatesInBaseline =
          ImmutableMultiset.builder();
      for (final KBPString clusterMate : clusterMates) {
        final Integer corefForClusterMate = newCASToCoref.get(clusterMate);
        if (corefForClusterMate != null) {
          // we don't have to worry about iterating over the target CAS itself
          // because we know it will never pass this check
          bCorefIDsOfClusterMatesInBaseline.add(corefForClusterMate);
          msg.append("\t\t\t").append(clusterMate).append(" ---> ")
              .append(corefForClusterMate).append("\n");
        } else {
          msg.append("\t\t\t").append(clusterMate).append(" ---> unknown\n");
        }
      }

      final ImmutableMultiset<Integer> corefIDsOfClusterMatesInBaseline =
          bCorefIDsOfClusterMatesInBaseline.build();

      final int newCorefIdx;
      if (!corefIDsOfClusterMatesInBaseline.isEmpty()) {
        // we know this will be non-null due to the above check
        newCorefIdx = getFirst(copyHighestCountFirst(corefIDsOfClusterMatesInBaseline), null);
        msg.append("\t\tMapping to dominant cluster mate cluster ").append(newCorefIdx)
            .append("\n");
      } else {
        // if we had no clustermates with known coref indices, start a new cluster.
        // When it comes time to assign coref to our clustermates, if any,
        // then we know they will have at least one clustermate with a known coref ID
        newCorefIdx = nextIndex;
        nextIndex = nextFreeIndex(nextIndex, newCASToCoref);
        msg.append("\t\tMapping to new cluster ").append(newCorefIdx).append("\n");
      }
      log.info(msg.toString());
      newCASToCoref.put(CAS, newCorefIdx);
      ret.corefCAS(CAS, newCorefIdx);
    }
  }

  for (final KBPString unannotatedCAS : toMerge.unannotated) {
    ret.addUnannotatedCAS(unannotatedCAS);
  }

  return ret.build();
}
 
Example 17
Project: Phoenix-for-VK   File: KeyExchangeSession.java   View Source Code Vote up 4 votes
public int getEndMessageId(){
    return Collections.max(messageIds);
}
 
Example 18
Project: KingdomFactions   File: Faction.java   View Source Code Vote up 4 votes
/**
public INexus getClosestNexus(KingdomFactionsPlayer player) {
	HashMap<INexus, Double> distance = new HashMap<INexus, Double>();
	for (INexus n : NexusModule.getInstance().getNexuses()) {
		Location nexusloc = Utils.getInstance().getNewLocation(n.getNexusLocation());
		Location playerloc = Utils.getInstance().getNewLocation(player.getLocation());
		nexusloc.setY(0);
		playerloc.setY(0);
		distance.put(n, nexusloc.distance(playerloc));
	}
	double minValueInMap = (Collections.min(distance.values()));
	if (distance.isEmpty()) {
		return null;
	}
	for (Entry<INexus, Double> entry : distance.entrySet()) {
		if (entry.getValue() == minValueInMap) {
			entry.getKey(); // nexus
			entry.getValue();// value
			return entry.getKey();

		}
	}
	return null;
}
*/


public Nexus getBestNexus() {
	HashMap<Nexus, Integer> levels = new HashMap<Nexus, Integer>();
	for(Nexus n : this.getNexuses()) {
		levels.put(n, n.getLevel());
	}
	int maxValueInMap = (Collections.max(levels.values()));
	for(Entry<Nexus, Integer> entry : levels.entrySet()) {
		if(entry.getValue() == maxValueInMap) {
			return entry.getKey();
		}
	}
	return null;
  }
 
Example 19
Project: Explainer   File: ExplainerUtils.java   View Source Code Vote up 4 votes
public static List<Double> weightedSamplingWithReplacement(List<Double> values,
    List<Double> weights, int numberOfSamples) {

  int minIndex, maxIndex, sampleIndex;
  int size = values.size();
  // Calculating the next power of two
  int power = (int) Math.ceil(Math.log((double) size) / Math.log(2));
  int numPartitions = (int) Math.pow(2, power);
  double minValue, maxValue, remainingCapacity, sample, w, elementWeight;
  double capacity = 1.00 / numPartitions;
  List<Double> partition, samplePartition;
  SecureRandom random = new SecureRandom();

  List<List<Double>> listPartitions = new ArrayList<>(numPartitions);
  for (int i = 0; i < numPartitions; i++) {
    partition = new ArrayList<Double>();
    minValue = Collections.min(weights);
    minIndex = weights.indexOf(minValue);
    partition.add((double) minIndex);
    if (minValue >= capacity) {
      weights.set(minIndex, (minValue - capacity));
      partition.add(-1.00);
      partition.add(1.00);
    } else {
      remainingCapacity = capacity - minValue;
      maxValue = Collections.max(weights);
      maxIndex = weights.indexOf(maxValue);
      partition.add((double) maxIndex);
      partition.add(minValue / capacity);
      weights.set(minIndex, 0.0);
      weights.set(maxIndex, (maxValue - remainingCapacity));
    }
    listPartitions.add(partition);
  }

  List<Double> samples = new ArrayList<>();
  for (int i = 0; i < numberOfSamples; i++) {
    sample = random.nextDouble() * numPartitions;
    sampleIndex = (int) sample;
    w = sample - sampleIndex;
    samplePartition = listPartitions.get(sampleIndex);
    elementWeight = samplePartition.get(2);
    if (w <= elementWeight) {
      samples.add(values.get(samplePartition.get(0).intValue()));
    } else {
      samples.add(values.get(samplePartition.get(1).intValue()));
    }
  }
  return samples;

}
 
Example 20
Project: athena   File: DefaultMetricsDatabase.java   View Source Code Vote up 4 votes
private double maxMetric(String metricType, long startTime, long endTime) {
    double[] all = metrics(metricType, startTime, endTime);
    List list = Arrays.asList(ArrayUtils.toObject(all));
    return (double) Collections.max(list);
}