当前位置: 首页>>代码示例>>Java>>正文


Java Map.getOrDefault方法代码示例

本文整理汇总了Java中java.util.Map.getOrDefault方法的典型用法代码示例。如果您正苦于以下问题:Java Map.getOrDefault方法的具体用法?Java Map.getOrDefault怎么用?Java Map.getOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.Map的用法示例。


在下文中一共展示了Map.getOrDefault方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: deserialize

import java.util.Map; //导入方法依赖的package包/类
public static SubscribeMessage deserialize(JsonParser jp) throws IOException {
	jp.nextToken();
	long request = jp.getLongValue();

	MatchPolicy match = MatchPolicy.EXACT;

	jp.nextToken();
	boolean getRetained = false;
	Map<String, Object> options = ParserUtil.readObject(jp);
	if (options != null) {
		String extValue = (String) options.get("match");
		if (extValue != null) {
			match = MatchPolicy.fromExtValue(extValue);
			if (match == null) {
				match = MatchPolicy.EXACT;
			}
		}
		getRetained = (boolean) options.getOrDefault("get_retained", false);
	}

	jp.nextToken();
	String topic = jp.getValueAsString();

	return new SubscribeMessage(request, topic, match, getRetained);
}
 
开发者ID:ralscha,项目名称:wamp2spring,代码行数:26,代码来源:SubscribeMessage.java

示例2: fetchSessionId

import java.util.Map; //导入方法依赖的package包/类
/**
 * <p>It isn't possible to follow
 * <a href="https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html">Oracle Accessing Cookies Tutorial</a>
 * via default {@link CookieManager} with {@link java.net.InMemoryCookieStore} under the hood.
 *
 * <p>{@link CookieManager} is the implementation of <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>.
 * But the website needs to implement <a href="http://www.ietf.org/rfc/rfc6265.txt">RFC 6265</a>.
 *
 * <p>RFC 2965: "x.y.com domain-matches .Y.com but not Y.com."<br/>
 * RFC 6265: "The domain string is a suffix of the string. The last character of the string that is not included in the domain string is a "." character." <br/>
 * Take a look at <a href="https://github.com/square/okhttp/issues/991">OkHttp #991</a>.
 *
 * <p>So, private {@link com.sun.webkit.network.CookieManager} is implementing RFC 6265, that's why it's using.
 *
 * @return session id if it exists or {@code null}
 */
@SneakyThrows
private String fetchSessionId() {
    Map<String, List<String>> headers = CookieManager.getDefault().get(COOKIE_DOMAIN_URI, new HashMap<>());
    List<String> values = headers.getOrDefault("Cookie", new ArrayList<>());
    if (values.isEmpty()) {
        return null;
    }

    String headerValue = values.get(0);
    String[] cookieEntries = headerValue.split(";");
    for (String cookieEntry : cookieEntries) {
        String[] cookieParts = cookieEntry.split("=");
        if ("remixsid".equals(cookieParts[0].trim())) {
            return cookieParts[1].trim();
        }
    }

    return null;
}
 
开发者ID:ruslanys,项目名称:vkmusic,代码行数:36,代码来源:LoginController.java

示例3: getStoredProcedures

import java.util.Map; //导入方法依赖的package包/类
protected Map<String, StoredProcedureMetadata> getStoredProcedures(final Map<String, Object> parameters) {

        final Map<String, StoredProcedureMetadata> storedProcedures = new HashMap<>();

        try (Connection connection = DriverManager.getConnection(String.valueOf(parameters.get("url")),
            String.valueOf(parameters.get("user")), String.valueOf(parameters.get("password")));) {

            final DatabaseMetaData meta = connection.getMetaData();
            final String catalog = (String) parameters.getOrDefault("catalog", null);
            final String defaultSchema = DatabaseMetaDataHelper.getDefaultSchema(
                    meta.getDatabaseProductName(), String.valueOf(parameters.get("user")));
            final String schemaPattern = (String) parameters.getOrDefault("schema-pattern", defaultSchema);
            final String procedurePattern = (String) parameters.getOrDefault("procedure-pattern", null);

            try (ResultSet procedureSet = DatabaseMetaDataHelper.fetchProcedures(meta, catalog, schemaPattern, procedurePattern)) {
                while (procedureSet.next()) {
                    final String name = procedureSet.getString("PROCEDURE_NAME");
                    final StoredProcedureMetadata storedProcedureMetadata = getStoredProcedureMetadata(connection,
                        catalog, schemaPattern, name);
                    storedProcedureMetadata.setName(procedureSet.getString("PROCEDURE_NAME"));
                    storedProcedureMetadata.setType(procedureSet.getString("PROCEDURE_TYPE"));
                    storedProcedureMetadata.setRemark(procedureSet.getString("REMARKS"));
                    storedProcedures.put(storedProcedureMetadata.getName(), storedProcedureMetadata);
                }
            }
            return storedProcedures;

        } catch (final SQLException e) {
            throw new IllegalStateException(e);
        }
    }
 
开发者ID:syndesisio,项目名称:syndesis,代码行数:32,代码来源:SqlStoredConnectorMetaDataExtension.java

示例4: test

import java.util.Map; //导入方法依赖的package包/类
private static void test(final Shift shift, final Param param) {
	try {
		final XOR64ShiftRandom random = new XOR64ShiftRandom(
			shift,
			param,
			XOR64ShiftRandom.seedBytes()
		);

		final List<Result> results = DieHarder
			.test(random, singletonList("-a"), System.out);

		final Map<Assessment, Long> grouped = results.stream()
			.collect(groupingBy(r -> r.assessment, counting()));

		final long passed = grouped.getOrDefault(Assessment.PASSED, 0L);
		final long weak = grouped.getOrDefault(Assessment.WEAK, 0L);
		final long failed = grouped.getOrDefault(Assessment.FAILED, 0L);

		synchronized (System.err) {
			System.err.println(format(
				"%d; %d; %d; %d; %s",
				(passed - failed), passed, weak, failed, param
			));
		}

	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
开发者ID:jenetics,项目名称:prngine,代码行数:30,代码来源:XOR64ShiftRandomParamTest.java

示例5: main

import java.util.Map; //导入方法依赖的package包/类
public static void main(final String[] args) throws Exception {
    final Map<String, String> opts = argsToOpts(Arrays.asList(args));
    applySystemProperties(opts);
    final String name = opts.getOrDefault("name", "coffee-house");

    final ActorSystem system = ActorSystem.create(String.format("%s-system", name));
    final CoffeeHouseApp coffeeHouseApp = new CoffeeHouseApp(system);
    coffeeHouseApp.run();
}
 
开发者ID:ironfish,项目名称:oreilly-reactive-with-akka,代码行数:10,代码来源:CoffeeHouseApp.java

示例6: main

import java.util.Map; //导入方法依赖的package包/类
public static void main(final String[] args) throws Exception {
    final Map<String, String> opts = argsToOpts(Arrays.asList(args));
    applySystemProperties(opts);
    final String name = opts.getOrDefault("name", "guestapp");

    final ActorSystem system = ActorSystem.create(String.format("%s-system", name), ConfigFactory.load("guest.conf"));
    final GuestApp guestApp = new GuestApp(system);
    guestApp.run();
}
 
开发者ID:ironfish,项目名称:oreilly-reactive-architecture-old,代码行数:10,代码来源:GuestApp.java

示例7: immunizationDue

import java.util.Map; //导入方法依赖的package包/类
@SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean immunizationDue(String immunization, Person person, long time,
    Map<String, List<Long>> immunizationsGiven) {
  int ageInMonths = person.ageInMonths(time);

  List<Long> history = null;
  if (immunizationsGiven.containsKey(immunization)) {
    history = immunizationsGiven.get(immunization);
  } else {
    history = new ArrayList<Long>();
    immunizationsGiven.put(immunization, history);
  }

  // Don't administer if the immunization wasn't historically available at the date of the
  // encounter
  Map schedule = immunizationSchedule.get(immunization);
  Double firstAvailable = (Double) schedule.getOrDefault("first_available", 1900);
  if (time < Utilities.convertCalendarYearsToTime(firstAvailable.intValue())) {
    return false;
  }

  // Don't administer if all recommended doses have already been given
  List atMonths = new ArrayList((List) schedule.get("at_months"));
  if (history.size() >= atMonths.size()) {
    return false;
  }

  // See if the patient should receive a dose based on their current age and the recommended dose
  // ages;
  // we can't just see if greater than the recommended age for the next dose they haven't received
  // because i.e. we don't want to administer the HPV vaccine to someone who turns 90 in 2006 when
  // the
  // vaccine is released; we can't just use a simple test of, say, within 4 years after the
  // recommended
  // age for the next dose they haven't received because i.e. PCV13 is given to kids and seniors
  // but was
  // only available starting in 2010, so a senior in 2012 who has never received a dose should get
  // one,
  // but only one; what we do is:

  // 1) eliminate any recommended doses that are not within 4 years of the patient's age
  // at_months = at_months.reject { |am| age_in_months - am >= 48 }
  Predicate<Double> notWithinFourYears = p -> ((ageInMonths - p) >= 48);
  atMonths.removeIf(notWithinFourYears);
  if (atMonths.isEmpty()) {
    return false;
  }

  // 2) eliminate recommended doses that were actually administered
  for (Long date : history) {
    int ageAtDate = person.ageInMonths(date);
    double recommendedAge = (double) atMonths.get(0);
    if (ageAtDate >= recommendedAge && ((ageAtDate - recommendedAge) < 48)) {
      atMonths.remove(0);
      if (atMonths.isEmpty()) {
        return false;
      }
    }
  }

  // 3) see if there are any recommended doses remaining that this patient is old enough for
  return !atMonths.isEmpty() && ageInMonths >= (double) atMonths.get(0);
}
 
开发者ID:synthetichealth,项目名称:synthea_java,代码行数:64,代码来源:Immunizations.java

示例8: recalculateStats

import java.util.Map; //导入方法依赖的package包/类
/**
 * Locks and resets all stats and recalculates all
 * @param broadcast
 */
public final void recalculateStats(boolean broadcast)
{
	_lock.writeLock().lock();
	try
	{
		// Copy old data before wiping it out
		final Map<Stats, Double> adds = !broadcast ? Collections.emptyMap() : new HashMap<>(_statsAdd);
		final Map<Stats, Double> muls = !broadcast ? Collections.emptyMap() : new HashMap<>(_statsMul);
		
		// Wipe all the data
		resetStats();
		
		// Collect all necessary effects
		final CharEffectList effectList = _activeChar.getEffectList();
		final Stream<BuffInfo> passives = effectList.hasPassives() ? effectList.getPassives().stream().filter(info -> info.getSkill().checkConditions(SkillConditionScope.PASSIVE, _activeChar, _activeChar)) : null;
		final Stream<BuffInfo> options = effectList.hasOptions() ? effectList.getOptions().stream() : null;
		final Stream<BuffInfo> effectsStream = Stream.concat(effectList.getEffects().stream(), Stream.concat(passives != null ? passives : Stream.empty(), options != null ? options : Stream.empty()));
		
		// Call pump to each effect
		//@formatter:off
		effectsStream.forEach(info -> info.getEffects().stream()
			.filter(effect -> effect.canStart(info))
			.filter(effect -> effect.canPump(info.getEffector(), info.getEffected(), info.getSkill()))
			.forEach(effect -> effect.pump(info.getEffected(), info.getSkill())));
		//@formatter:on
		
		// Merge with additional stats
		_additionalAdd.stream().filter(holder -> holder.verifyCondition(_activeChar)).forEach(holder -> mergeAdd(holder.getStat(), holder.getValue()));
		_additionalMul.stream().filter(holder -> holder.verifyCondition(_activeChar)).forEach(holder -> mergeMul(holder.getStat(), holder.getValue()));
		
		// Notify recalculation to child classes
		onRecalculateStats(broadcast);
		
		if (broadcast)
		{
			// Calculate the difference between old and new stats
			final Set<Stats> changed = new HashSet<>();
			for (Stats stat : Stats.values())
			{
				if (_statsAdd.getOrDefault(stat, stat.getResetAddValue()) != adds.getOrDefault(stat, stat.getResetAddValue()))
				{
					changed.add(stat);
				}
				else if (_statsMul.getOrDefault(stat, stat.getResetMulValue()) != muls.getOrDefault(stat, stat.getResetMulValue()))
				{
					changed.add(stat);
				}
			}
			
			_activeChar.broadcastModifiedStats(changed);
		}
	}
	finally
	{
		_lock.writeLock().unlock();
	}
}
 
开发者ID:rubenswagner,项目名称:L2J-Global,代码行数:62,代码来源:CharStat.java

示例9: preHandle

import java.util.Map; //导入方法依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    if (isIgnoredRequest(request)) {
        return true;
    }

    try {
        String tenant;
        final OAuth2Authentication auth = getAuthentication();
        if (auth == null) {
            tenant = request.getHeader(HEADER_TENANT);
            TenantContext.setCurrent(tenant);
        } else {
            Map<String, String> details = null;

            if (auth.getDetails() != null) {
                details = Map.class.cast(OAuth2AuthenticationDetails.class.cast(auth.getDetails())
                                             .getDecodedDetails());
            }

            if (details == null) {
                details = new HashMap<>();
            }

            tenant = details.getOrDefault(AUTH_TENANT_KEY, "");

            String xmToken = details.getOrDefault(AUTH_XM_TOKEN_KEY, "");
            String xmCookie = details.getOrDefault(AUTH_XM_COOKIE_KEY, "");
            String xmUserId = details.getOrDefault(AUTH_XM_USERID_KEY, "");
            String xmLocale = details.getOrDefault(AUTH_XM_LOCALE, "");
            String xmUserLogin = (String) auth.getPrincipal();
            String xmUserKey = details.getOrDefault(AUTH_USER_KEY, "");


            TenantContext.setCurrent(new TenantInfo(tenant, xmToken, xmCookie, xmUserId, xmLocale,
                xmUserLogin, xmUserKey));

            Locale locale = LocaleUtils.getLocaleFromString(xmLocale);
            if (locale != null) {
                LocaleContextHolder.setLocale(locale);
            }
        }

        final boolean tenantSet;
        if (StringUtils.isBlank(tenant)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write("{\"error\": \"No tenant supplied\"}");
            response.getWriter().flush();
            tenantSet = false;
        } else if (tenantListRepository.getSuspendedTenants().contains(tenant.toLowerCase())) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write("{\"error\": \"Tenant is suspended\"}");
            response.getWriter().flush();
            tenantSet = false;
        } else {
            tenantSet = true;
        }

        return tenantSet;
    } catch (Exception e) {
        log.error("Error in tenant interceptor: ", e);
        throw e;
    }
}
 
开发者ID:xm-online,项目名称:xm-ms-dashboard,代码行数:69,代码来源:TenantInterceptor.java

示例10: modelState

import java.util.Map; //导入方法依赖的package包/类
public synchronized LinearRegressionModelState modelState() {
  Map<Integer, Double> detailCompleteness = new HashMap<>();
  for (Map.Entry<Integer, AtomicInteger> entry : INDICES.entrySet()) {
    detailCompleteness.put(entry.getKey(),
                           Math.min((double) entry.getValue().get() / NUM_OBSERVATIONS_PER_UTIL_BUCKET, 1.0));
  }
  Map<Integer, Integer> usedLeaderToFollowerRatio = new HashMap<>();
  Map<Integer, Integer> usedLeaderBytesInToBytesOutRatio = new HashMap<>();
  Map<ModelCoefficient, Double> coefficientFromAvailableData = new HashMap<>(_coefficients);
  OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
  regression.setNoIntercept(true);
  boolean ignoreLeaderBytesOutRate = !isLeaderBytesInAndOutRatioDiverseEnough();
  double[][] sampleBytesRateData = aggregateSampleBytesRateData(ignoreLeaderBytesOutRate);

  int leaderBytesInIndex = 0;
  int leaderBytesOutIndex = 1;
  int followerBytesInIndex = ignoreLeaderBytesOutRate ? 1 : 2;
  for (int i = 0; i < sampleBytesRateData.length; i++) {
    int leaderToFollowerRatio = sampleBytesRateData[i][followerBytesInIndex] == 0.0 ? 10000000 :
        (int) ((sampleBytesRateData[i][leaderBytesInIndex] / sampleBytesRateData[i][followerBytesInIndex]) * 10);
    int count = usedLeaderToFollowerRatio.getOrDefault(leaderToFollowerRatio, 0);
    usedLeaderToFollowerRatio.put(leaderToFollowerRatio, count + 1);

    if (!ignoreLeaderBytesOutRate) {
      int leaderBytesInToBytesOutRatio = sampleBytesRateData[i][leaderBytesOutIndex] == 0.0 ? 10000000 :
          (int) ((sampleBytesRateData[i][leaderBytesInIndex] / sampleBytesRateData[i][leaderBytesOutIndex]) * 10);
      count = usedLeaderBytesInToBytesOutRatio.getOrDefault(leaderBytesInToBytesOutRatio, 0);
      usedLeaderBytesInToBytesOutRatio.put(leaderBytesInToBytesOutRatio, count + 1);
    }
  }
  regression.newSampleData(aggregateSampleCpuUtilData(), sampleBytesRateData);
  double[] parameters = regression.estimateRegressionParameters();
  coefficientFromAvailableData.put(ModelCoefficient.LEADER_BYTES_IN, parameters[leaderBytesInIndex]);
  if (ignoreLeaderBytesOutRate) {
    coefficientFromAvailableData.put(ModelCoefficient.FOLLOWER_BYTES_IN, parameters[followerBytesInIndex]);
  } else {
    coefficientFromAvailableData.put(ModelCoefficient.LEADER_BYTES_OUT, parameters[leaderBytesOutIndex]);
    coefficientFromAvailableData.put(ModelCoefficient.FOLLOWER_BYTES_IN, parameters[followerBytesInIndex]);
  }
  return new LinearRegressionModelState(detailCompleteness, coefficientFromAvailableData,
                                        OBSERVED_LEADER_TO_FOLLOWER_BYTES_RATIO,
                                        OBSERVED_LEADER_BYTES_IN_TO_BYTES_OUT_RATIO,
                                        usedLeaderToFollowerRatio, usedLeaderBytesInToBytesOutRatio,
                                        CPU_UTIL_ESTIMATION_ERROR_STATS);
}
 
开发者ID:linkedin,项目名称:cruise-control,代码行数:46,代码来源:LinearRegressionModelParameters.java

示例11: AnalogInputData

import java.util.Map; //导入方法依赖的package包/类
public AnalogInputData(Map<String, Object> map) {
  this((String) map.getOrDefault("Name", "?"), (double) map.getOrDefault("Value", 0.0));
}
 
开发者ID:wpilibsuite,项目名称:shuffleboard,代码行数:4,代码来源:AnalogInputData.java

示例12: test

import java.util.Map; //导入方法依赖的package包/类
public static List<Result> test(
	final Random random,
	final List<String> args,
	final PrintStream out
)
	throws IOException, InterruptedException
{
	final List<String> dieharderArgs = new ArrayList<>();
	dieharderArgs.add("dieharder");
	dieharderArgs.addAll(args);
	dieharderArgs.add("-g");
	dieharderArgs.add("200");

	printv(out);

	final long start = System.currentTimeMillis();
	final ProcessBuilder builder = new ProcessBuilder(dieharderArgs);
	final Process dieharder = builder.start();

	final Randomizer randomizer = new Randomizer(
		random,
		dieharder.getOutputStream()
	);
	final Thread randomizerThread = new Thread(randomizer);
	randomizerThread.start();

	// The dieharder console output.
	final BufferedReader stdout = new BufferedReader (
		new InputStreamReader(dieharder.getInputStream())
	);

	final List<Result> results = new ArrayList<>();
	for (String l = stdout.readLine(); l != null; l = stdout.readLine()) {
		Result.parse(l).ifPresent(results::add);
		System.out.println(l);
	}

	dieharder.waitFor();
	randomizerThread.interrupt();

	final long millis = System.currentTimeMillis() - start;
	final long sec = millis/1000;
	final double megaBytes = randomizer.getCount()/(1024.0*1024.0);

	// Calculate statistics.
	final Map<Assessment, Long> grouped = results.stream()
		.collect(groupingBy(r -> r.assessment, counting()));

	final long passed = grouped.getOrDefault(Assessment.PASSED, 0L);
	final long weak = grouped.getOrDefault(Assessment.WEAK, 0L);
	final long failed = grouped.getOrDefault(Assessment.FAILED, 0L);

	final NumberFormat formatter = NumberFormat.getIntegerInstance();
	formatter.setMinimumFractionDigits(3);
	formatter.setMaximumFractionDigits(3);

	println(out, "#=============================================================================#");
	println(out,
		"# %-76s#",
		format("Summary: PASSED=%d, WEAK=%d, FAILED=%d", passed, weak, failed)
	);
	println(out,
		"# %-76s#",
		format("         %s MB of random data created with %s MB/sec",
			formatter.format(megaBytes),
			formatter.format(megaBytes/(millis/1000.0))
		)
	);
	println(out, "#=============================================================================#");
	printt(out, "Runtime: %d:%02d:%02d", sec/3600, (sec%3600)/60, sec%60);

	return results;
}
 
开发者ID:jenetics,项目名称:prngine,代码行数:74,代码来源:DieHarder.java

示例13: deserialize

import java.util.Map; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
public static PublishMessage deserialize(JsonParser jp) throws IOException {
	jp.nextToken();
	long request = jp.getLongValue();

	boolean acknowledge = false;
	boolean excludeMe = true;
	boolean discloseMe = false;
	boolean retain = false;
	Set<Number> exclude = null;
	Set<Number> eligible = null;
	jp.nextToken();
	Map<String, Object> options = ParserUtil.readObject(jp);
	if (options != null) {
		acknowledge = (boolean) options.getOrDefault("acknowledge", false);
		excludeMe = (boolean) options.getOrDefault("exclude_me", true);
		discloseMe = (boolean) options.getOrDefault("disclose_me", false);
		retain = (boolean) options.getOrDefault("retain", false);

		List<Number> excludeArray = (List<Number>) options.get("exclude");
		if (excludeArray != null) {
			exclude = new HashSet<>(excludeArray);
		}

		List<Number> eligibleArray = (List<Number>) options.get("eligible");
		if (eligibleArray != null) {
			eligible = new HashSet<>(eligibleArray);
		}
	}

	jp.nextToken();
	String topic = jp.getValueAsString();

	List<Object> arguments = null;
	JsonToken token = jp.nextToken();
	if (token == JsonToken.START_ARRAY) {
		arguments = ParserUtil.readArray(jp);
	}

	Map<String, Object> argumentsKw = null;
	token = jp.nextToken();
	if (token == JsonToken.START_OBJECT) {
		argumentsKw = ParserUtil.readObject(jp);
	}

	return new PublishMessage(request, topic, arguments, argumentsKw, acknowledge,
			excludeMe, discloseMe, retain, exclude, eligible);
}
 
开发者ID:ralscha,项目名称:wamp2spring,代码行数:49,代码来源:PublishMessage.java

示例14: apply

import java.util.Map; //导入方法依赖的package包/类
@Override
public String apply(String in, Map<String, String> state) {
    return state.getOrDefault(key, "");
}
 
开发者ID:glispa,项目名称:combo,代码行数:5,代码来源:ParameterMacro.java


注:本文中的java.util.Map.getOrDefault方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。