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

The following examples show how to use java.util.Collections#max() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: plexus   File: GetEmotion.java    License: MIT License 6 votes vote down vote up
/**
 * Find the emotion with the largest relevance value using a created HashMap
 * 
 * @param e1
 * @param e2
 * @param e3
 * @param e4
 * @param e5
 * @return Final Emotion
 */
public static String getFinalEmotion(double e1, double e2, double e3,
        double e4, double e5) {
    // Create a map that stores the keys and values of the emotion 
    // analysis results
    HashMap<String, Double> map = new HashMap<>();
    map.put("Joy", e1);
    map.put("Anger", e2);
    map.put("Fear", e3);
    map.put("Sadness", e4);
    map.put("Disgust", e5);

    Map.Entry<String, Double> maxEntry = null;
    
    // Now look for the variable with the maximum in the created HashMap
    double maxValueInMap = (Collections.max(map.values()));  // This will return max value in the Hashmap
    map.entrySet().stream().filter((entry) -> (entry.getValue() == maxValueInMap)).forEachOrdered((entry) -> {
        // System.out.println(entry.getKey());     // Print the key with max value
        finalEmotion = (String) entry.getKey();
    }); // Itrate through HashMap to find the max
    return finalEmotion; // this the emotion with the largest relevance value
}
 
Example 2
Source Project: TensorFlowOnYARN   File: ClusterSpec.java    License: Apache License 2.0 6 votes vote down vote up
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 3
@Test
public void testEvennessByDefaultConstraint() {
  Map<String, Map<String, Map<String, String>>> result = new HashMap<>();

  ConstraintRebalanceStrategy strategy = new ConstraintRebalanceStrategy();

  for (String resourceName : resourceNames) {
    Map<String, Map<String, String>> partitionMap = new HashMap<>();

    strategy.init(resourceName, partitions, states, Integer.MAX_VALUE);
    partitionMap.putAll(strategy.computePartitionAssignment(instanceNames, instanceNames,
        new HashMap<String, Map<String, String>>(), cache).getMapFields());
    result.put(resourceName, partitionMap);
  }

  Map<String, Integer> weightCount = checkPartitionUsage(result, new PartitionWeightProvider() {
    @Override
    public int getPartitionWeight(String resource, String partition) {
      return 1;
    }
  });
  int max = Collections.max(weightCount.values());
  int min = Collections.min(weightCount.values());
  // Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of participant capacity in max.
  Assert.assertTrue((max - min) <= defaultCapacity / 100);
}
 
Example 4
Source Project: gemfirexd-oss   File: FunctionHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Apply the Minimum function on given list of number
 * 
 * @param vals
 *                Array of number
 */
public static final Number MIN(Number[] vals) {
  try {
    Collection col = Arrays.asList(vals);
    Number min = (Number)Collections.max(col);

    return min;
  }
  catch (Throwable t) {
    Error err;
    if (t instanceof Error && SystemFailure.isJVMFailureError(
        err = (Error)t)) {
      SystemFailure.initiateFailure(err);
      // If this ever returns, rethrow the error. We're poisoned
      // now, so don't let this thread continue.
      throw err;
    }
    // Whenever you catch Error or Throwable, you must also
    // check for fatal JVM error (see above).  However, there is
    // _still_ a possibility that you are dealing with a cascading
    // error condition, so you also need to check to see if the JVM
    // is still usable:
    SystemFailure.checkFailure();
    return null;
  }
}
 
Example 5
Source Project: find   File: TrendingService.java    License: MIT License 5 votes vote down vote up
public Float yAxisLabelRange(final TrendingView trendingView) {
    final List<WebElement> yAxisTicks = trendingView.yAxisTicks();
    final List<Float> valueArray = yAxisTicks
        .stream()
        .map(label -> label.getText().isEmpty() ? 0f : parseFormattedDecimal(label).floatValue())
        .collect(Collectors.toList());
    return yAxisTicks.isEmpty() ? 0f : Collections.max(valueArray) - Collections.min(valueArray);
}
 
Example 6
public DebtRecoveryHistory getDebtRecoveryHistory(DebtRecovery detDebtRecovery) {
  if (detDebtRecovery.getDebtRecoveryHistoryList() == null
      || detDebtRecovery.getDebtRecoveryHistoryList().isEmpty()) {
    return null;
  }
  return Collections.max(
      detDebtRecovery.getDebtRecoveryHistoryList(),
      Comparator.comparing(DebtRecoveryHistory::getDebtRecoveryDate));
}
 
Example 7
Source Project: Flink-CEPplus   File: TupleTypeInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TypeComparator<T> createTypeComparator(ExecutionConfig config) {
	checkState(
		fieldComparators.size() > 0,
		"No field comparators were defined for the TupleTypeComparatorBuilder."
	);

	checkState(
		logicalKeyFields.size() > 0,
		"No key fields were defined for the TupleTypeComparatorBuilder."
	);

	checkState(
		fieldComparators.size() == logicalKeyFields.size(),
		"The number of field comparators and key fields is not equal."
	);

	final int maxKey = Collections.max(logicalKeyFields);

	checkState(
		maxKey >= 0,
		"The maximum key field must be greater or equal than 0."
	);

	TypeSerializer<?>[] fieldSerializers = new TypeSerializer<?>[maxKey + 1];

	for (int i = 0; i <= maxKey; i++) {
		fieldSerializers[i] = types[i].createSerializer(config);
	}

	return new TupleComparator<T>(
		listToPrimitives(logicalKeyFields),
		fieldComparators.toArray(new TypeComparator[fieldComparators.size()]),
		fieldSerializers
	);
}
 
Example 8
Source Project: ExpectIt   File: MultiMatcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Find the result with the maximum end position and use it as delegate.
 */
private static Result findResultWithMaxEnd(List<Result> successResults) {
    return Collections.max(
            successResults, new Comparator<Result>() {
                @Override
                public int compare(Result o1, Result o2) {
                    return Integer.valueOf(o1.end()).compareTo(o2.end());
                }
            });
}
 
Example 9
@Override
public Sar buildSar(List<RxnMolecule> reactions) {
  if (!DbAPI.areAllOneSubstrate(reactions)) {
    throw new IllegalArgumentException("Reactions are not all one substrate.");
  }

  List<Integer> carbonCounts = getSubstrateCarbonCounts(reactions);
  return new OneSubstrateCarbonCountSar(Collections.min(carbonCounts), Collections.max(carbonCounts));
}
 
Example 10
/**
 * 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 11
public boolean[] getUseMediaType() {
    Set<Integer> keys = getMediatypes().keySet();
    boolean[] result = new boolean[Collections.max(keys) + 1];
    for (Integer key: keys) {
        result[key] = getUseMediaType(key);
    }
    return result;
}
 
Example 12
Source Project: EZFilter   File: Camera2FilterActivity.java    License: MIT License 5 votes vote down vote up
private 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 {
        return choices[0];
    }
}
 
Example 13
@VisibleForTesting
static char[][] createReplacementArray(Map<Character, String> map) {
  checkNotNull(map); // GWT specific check (do not optimize)
  if (map.isEmpty()) {
    return EMPTY_REPLACEMENT_ARRAY;
  }
  char max = Collections.max(map.keySet());
  char[][] replacements = new char[max + 1][];
  for (char c : map.keySet()) {
    replacements[c] = map.get(c).toCharArray();
  }
  return replacements;
}
 
Example 14
Source Project: querqy   File: SuffixTrieMap.java    License: Apache License 2.0 5 votes vote down vote up
public Optional<SuffixMatch<T>> getBySuffix(final CharSequence seq) {
    if (seq.length() == 0) {
        return Optional.empty();
    }

    final ReverseComparableCharSequence revSeq = new ReverseComparableCharSequence(seq);

    final States<T> states = trieMap.get(revSeq);

    final State<T> fullMatch = states.getStateForCompleteSequence();
    if (fullMatch.isFinal()) {
        return Optional.of(new SuffixMatch<>(0, fullMatch.value));
    }

    final List<State<T>> suffixMatches = states.getPrefixes();
    if (suffixMatches != null && !suffixMatches.isEmpty()) {
        final State<T> suffixMaxMatch = Collections.max(states.getPrefixes(), COMPARE_STATE_BY_INDEX_DESC);

        final int startSubstring = seq.length() - (suffixMaxMatch.index + 1);

        return Optional.of(new SuffixMatch<>(
                startSubstring,
                seq.subSequence(0, startSubstring),
                suffixMaxMatch.value));
    }

    return Optional.empty();
}
 
Example 15
Source Project: pinpoint   File: DownSamplers.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Integer sampleMax(Collection<Integer> values) {
    if (CollectionUtils.isEmpty(values)) {
        return this.defaultValue;
    }
    return Collections.max(values);
}
 
Example 16
public <T extends Versioned> T findLatest(Collection<T> elements) {
    return Collections.max(elements, this);
}
 
Example 17
@Override
public int getHighestAffectedQubitIndex() {
    return Collections.max(affected);
}
 
Example 18
Source Project: vjtools   File: CollectionUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 返回无序集合中的最大值,使用元素默认排序
 */
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
	return Collections.max(coll);
}
 
Example 19
Source Project: OEE-Designer   File: Helper.java    License: MIT License 4 votes vote down vote up
public static final Color getColorAt(final List<Stop> STOP_LIST, final double POSITION_OF_COLOR) {
	Map<Double, Stop> STOPS = new TreeMap<>();
	for (Stop stop : STOP_LIST) {
		STOPS.put(stop.getOffset(), stop);
	}

	if (STOPS.isEmpty())
		return Color.BLACK;

	double minFraction = Collections.min(STOPS.keySet());
	double maxFraction = Collections.max(STOPS.keySet());

	if (Double.compare(minFraction, 0d) > 0) {
		STOPS.put(0.0, new Stop(0.0, STOPS.get(minFraction).getColor()));
	}
	if (Double.compare(maxFraction, 1d) < 0) {
		STOPS.put(1.0, new Stop(1.0, STOPS.get(maxFraction).getColor()));
	}

	final double POSITION = clamp(0d, 1d, POSITION_OF_COLOR);
	final Color COLOR;
	if (STOPS.size() == 1) {
		// final Map<Double, Color> ONE_ENTRY = (Map<Double, Color>)
		// STOPS.entrySet().iterator().next();
		final Map.Entry<Double, Stop> ONE_ENTRY = STOPS.entrySet().iterator().next();
		// COLOR = STOPS.get(ONE_ENTRY.keySet().iterator().next()).getColor();
		COLOR = ONE_ENTRY.getValue().getColor();
	} else {
		Stop lowerBound = STOPS.get(0.0);
		Stop upperBound = STOPS.get(1.0);
		for (Double fraction : STOPS.keySet()) {
			if (Double.compare(fraction, POSITION) < 0) {
				lowerBound = STOPS.get(fraction);
			}
			if (Double.compare(fraction, POSITION) > 0) {
				upperBound = STOPS.get(fraction);
				break;
			}
		}
		COLOR = interpolateColor(lowerBound, upperBound, POSITION);
	}
	return COLOR;
}
 
Example 20
@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;

}