下面列出了怎么用java.util.StringJoiner的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Finds a constructor with the specified parameter types in the given class and makes it accessible.
* Note: For performance, store the returned value and avoid calling this repeatedly.
*
* <p>Throws an exception if the constructor is not found.</p>
*
* @param clazz The class to find the constructor in.
* @param parameterTypes The parameter types of the constructor.
* @param <T> The type.
* @return The constructor with the specified parameters in the given class.
* @throws NullPointerException If {@code clazz} is null.
* @throws NullPointerException If {@code parameterTypes} is null.
* @throws UnknownConstructorException If the constructor could not be found.
*/
@Nonnull
public static <T> Constructor<T> findConstructor(@Nonnull final Class<T> clazz, @Nonnull final Class<?>... parameterTypes) {
Preconditions.checkNotNull(clazz, "Class to find constructor on cannot be null.");
Preconditions.checkNotNull(parameterTypes, "Parameter types of constructor to find cannot be null.");
try {
Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
constructor.setAccessible(true);
return constructor;
} catch (final NoSuchMethodException e) {
final StringBuilder desc = new StringBuilder();
desc.append(clazz.getSimpleName());
StringJoiner joiner = new StringJoiner(", ", "(", ")");
for (Class<?> type : parameterTypes) {
joiner.add(type.getSimpleName());
}
desc.append(joiner);
throw new UnknownConstructorException("Could not find constructor '" + desc + "' in " + clazz);
}
}
/**
* Set the properties to ensure it points to correct referenced policy files. This will overwrite
* any previous properties set for referenced policies.
*
* @param properties Properties object that will get updated with referenced policy details
* @param referencedPolicies list of Paths to referenced Policies
* @return Properties object passed in
*/
public static Properties setXacmlReferencedProperties(Properties properties, Path... referencedPolicies) {
//
// Clear out the old entries
//
clearPolicyProperties(properties, XACMLProperties.PROP_REFERENCEDPOLICIES);
//
// Rebuild the list
//
int id = 1;
StringJoiner joiner = new StringJoiner(",");
for (Path policy : referencedPolicies) {
String ref = "ref" + id++;
joiner.add(ref);
properties.setProperty(ref + FILE_APPEND, policy.toAbsolutePath().toString());
}
properties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, joiner.toString());
return properties;
}
public void testEmptyBoth() {
StringJoiner sj = new StringJoiner(",", "{", "}");
StringJoiner other = new StringJoiner(":", "[", "]");
sj.merge(other);
assertEquals(sj.toString(), "{}");
other.setEmptyValue("NOTHING");
sj.merge(other);
assertEquals(sj.toString(), "{}");
sj = new StringJoiner(",", "{", "}").setEmptyValue("EMPTY");
assertEquals(sj.toString(), "EMPTY");
sj.merge(other);
assertEquals(sj.toString(), "EMPTY");
}
@Override
public String[] unparse(LoadContext context, Spell spell)
{
Changes<SpellSchool> changes = context.getObjectContext().getListChanges(spell, ListKey.SPELL_SCHOOL);
if (changes == null || changes.isEmpty())
{
return null;
}
StringJoiner joiner = new StringJoiner(Constants.PIPE);
if (changes.includesGlobalClear())
{
joiner.add(Constants.LST_DOT_CLEAR);
}
if (changes.hasAddedItems())
{
changes.getAdded().forEach(added -> joiner.add(added.toString()));
}
return new String[]{joiner.toString()};
}
@Override
public String[] unparse(LoadContext context, Spell spell)
{
Changes<String> changes = context.getObjectContext().getListChanges(spell, ListKey.SPELL_DESCRIPTOR);
if (changes == null || changes.isEmpty())
{
return null;
}
StringJoiner joiner = new StringJoiner(Constants.PIPE);
if (changes.includesGlobalClear())
{
joiner.add(Constants.LST_DOT_CLEAR);
}
if (changes.hasAddedItems())
{
changes.getAdded().forEach(added -> joiner.add(Objects.requireNonNull(added)));
}
return new String[]{joiner.toString()};
}
/**
* 简单处理入参URL
*
* @param url
* @return url
*/
@Override
public String insertUrlLogic(String url) {
// 处理逻辑 logic 表 url插入
List<MockUrlLogic> mockUrlLogics = mockUrlLogicService.insertByUrl(url);
// 转为map <subUrl, logicId>
Map<String, Long> urlAndId = mockUrlLogics.stream()
.collect(Collectors.toMap(MockUrlLogic::getSubUrl, MockUrlLogic::getLogicId));
// 处理logic字段
StringJoiner logicJoiner = new StringJoiner(COMMA);
// 根据url 转为对应的logic字符串
Arrays.stream(url.split("\\/")).filter(StrUtil::isNotBlank).map(i ->
// if {path} in url, return {path}
CommonConst.PATH_PLACEHOLDER.equalsIgnoreCase(i) ? CommonConst.PATH_PLACEHOLDER : urlAndId.get(i).toString()
).collect(Collectors.toList()).forEach(logicJoiner::add);
return logicJoiner.toString();
}
public String conllString() {
StringBuilder conllBuilder = new StringBuilder();
int i = 1;
for (ParseToken token : tokenLabels) {
String text = token.getText();
StringJoiner tokenBuilder = new StringJoiner("\t", "", "\n");
tokenBuilder.add(Integer.toString((i++))); // sentence position
tokenBuilder.add(text); // text
tokenBuilder.add("_"); // LEMMA
tokenBuilder.add("_"); // UPOSTAG
tokenBuilder.add("_"); // XPOSTAG
tokenBuilder.add("_"); // FEATS
tokenBuilder.add("_"); // HEAD
tokenBuilder.add("_"); // DEPREL
tokenBuilder.add("_"); // DEPS
tokenBuilder
.add(token.getHasSpaceAfter() ? "_" : "SpaceAfter=No"); // MISC
conllBuilder.append(tokenBuilder.toString());
}
return conllBuilder.toString();
}
private void ensureNonNullableCollectionArePresent(StructuredType entityType) throws ODataException {
if (getRequest().getMethod() != ODataRequest.Method.POST) {
return;
}
List<String> missingCollectionPropertyName = new ArrayList<>();
entityType.getStructuralProperties().stream()
.filter(property -> (property.isCollection()) &&
!(property instanceof NavigationProperty) && (!property.isNullable()))
.forEach(property -> {
LOG.debug("Validating non-nullable collection property : {}", property.getName());
if (!foundCollectionProperties.contains(property.getName())) {
missingCollectionPropertyName.add(property.getName());
}
});
if (missingCollectionPropertyName.size() != 0) {
StringJoiner joiner = new StringJoiner(",");
missingCollectionPropertyName.forEach(joiner::add);
LOG.debug("Non-nullable collections of {} are not found in the request" + missingCollectionPropertyName);
throw new ODataUnmarshallingException("The request does not specify the non-nullable collections: '"
+ joiner.toString() + ".");
}
}
private void printProof(State state) {
Stack<State> states = new Stack<>();
states.push(state);
while (state.previous != null) {
states.push(state.previous);
state = state.previous;
}
StringJoiner proof = new StringJoiner(" -> ");
while (!states.isEmpty()) {
proof.add(String.valueOf(states.pop().id));
}
StdOut.println(proof);
}
@NotNull
private static String toString(@NotNull final DriverCatalog ratio) {
return new StringJoiner(DELIMITER).add(ratio.chromosome())
.add(ratio.chromosomeBand())
.add(ratio.gene())
.add(String.valueOf(ratio.driver()))
.add(String.valueOf(ratio.category()))
.add(String.valueOf(ratio.likelihoodMethod()))
.add(FORMAT.format(ratio.driverLikelihood()))
.add(FORMAT.format(ratio.dndsLikelihood()))
.add(String.valueOf(ratio.missense()))
.add(String.valueOf(ratio.nonsense()))
.add(String.valueOf(ratio.splice()))
.add(String.valueOf(ratio.inframe()))
.add(String.valueOf(ratio.frameshift()))
.add(String.valueOf(ratio.biallelic()))
.add(FORMAT.format(ratio.minCopyNumber()))
.add(FORMAT.format(ratio.maxCopyNumber()))
.toString();
}
public String prettyPrint() {
StringJoiner joiner = new StringJoiner("\n");
items.stream()
.forEach(i -> joiner.add(String.format("\t%s: %s",
i.getColumn(),
i.getValue())));
return String.format("support: %f\n" +
"records: %f\n" +
"ratio: %f\n" +
"\nColumns:\n%s\n\n",
support,
numRecords,
ratioToInliers,
joiner.toString());
}
@Override
public String toString() {
return new StringJoiner("\t")
.add(Optional.ofNullable(this.alv.get())
.filter(v -> v > 0)
.map(v -> Messages.getString("item.alv", v)) //$NON-NLS-1$
.orElse(""))
.add(Optional.ofNullable(this.level.get())
.filter(v -> v > 0)
.map(v -> Messages.getString("item.level", v)) //$NON-NLS-1$
.orElse(""))
.add(Optional.ofNullable(this.ship.get())
.map(Ships::toName)
.orElse("未所持"))
.toString();
}
private String toStringDefault(ParenMode mode) {
boolean useParen = mode == ParenMode.ALWAYS;
if (!useParen) {
useParen = mode != ParenMode.NEVER && values.length > 1;
}
StringBuilder sb = new StringBuilder();
if (useParen) {
sb.append('(');
}
StringJoiner sj = new StringJoiner(joinString);
for (Value v : values) {
sj.add(formatField() + v.toString());
}
sb.append(sj.toString());
if (useParen) {
sb.append(')');
}
return sb.toString();
}
private String[] join(HashMap<String, Object> map) {
StringJoiner keys = new StringJoiner(",");
ParameterizedString parameterizedString = null;
HashMap<String, String> tmp = new HashMap<>();
for (Entry<String, Object> entry : map.entrySet()) {
keys.add(SQLHelper.wrapCol(entry.getKey()));
Object value = entry.getValue();
if (value instanceof ParameterizedString && value != parameterizedString) {
// TODO 18/3/8 multiple query, change to select .. a join b
// JdbcNestedQueryMapper & ParameterizedString
parameterizedString = (ParameterizedString) value;
} else {
tmp.put(entry.getKey(), SQLHelper.inSQL(value));
}
}
Assert.notNull(parameterizedString, "[Impossible to be null]");
parameterizedString.nameToAlias(tmp);
return new String[]{keys.toString(), parameterizedString.getSql()};
}
private String formatMethod(RecordedMethod m) {
StringBuilder sb = new StringBuilder();
sb.append(m.getType().getName());
sb.append(".");
sb.append(m.getName());
sb.append("(");
StringJoiner sj = new StringJoiner(", ");
String md = m.getDescriptor().replace("/", ".");
String parameter = md.substring(1, md.lastIndexOf(")"));
for (String qualifiedName : decodeDescriptors(parameter, "")) {
String typeName = qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
sj.add(typeName);
}
sb.append(sj);
sb.append(")");
return sb.toString();
}
/**
* 通过url查询logic字符串
*
* @param url 路径
* @return logic字符串
*/
@Override
public String selectLogicStrByUrl(String url) {
// 拆分为子url
List<String> subUrls = StrUtil.splitTrim(url, StrUtil.C_SLASH);
// empty -> put '/'
if (subUrls.isEmpty()) {
subUrls.add(StrUtil.SLASH);
}
// 查询对应logicId
List<MockUrlLogic> urlLogics = this.list(Wrappers.<MockUrlLogic>lambdaQuery()
// in 查询请求的url
.in(MockUrlLogic::getSubUrl, subUrls));
// 转为map
Map<String, Long> subUrlAndLogicId = urlLogics.stream().collect(Collectors.toMap(MockUrlLogic::getSubUrl, MockUrlLogic::getLogicId));
StringJoiner logicStrJoiner = new StringJoiner(StrUtil.COMMA);
// 删除空元素,循环拼接
subUrls.stream().filter(StrUtil::isNotBlank).forEach(item -> {
// 2.get logicId, ※ 如果是null,那么推测此处用户用了path传参, 则返回占位符!
Long logicId = subUrlAndLogicId.get(item);
// 拼接
logicStrJoiner.add(logicId == null ? CommonConst.PATH_PLACEHOLDER : logicId.toString());
});
return logicStrJoiner.toString();
}
@Test
public void allLookupKeysValid() throws IllegalAccessException {
// Collect all failed fields so the test results will show which field(s) failed
final StringJoiner sj = new StringJoiner(", ");
for (Field field : EquipmentTypeLookup.class.getFields()) {
if (field.isAnnotationPresent(EquipmentTypeLookup.EquipmentName.class)
&& ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)) {
String eqName = field.get(null).toString();
if (EquipmentType.get(eqName) == null) {
sj.add(eqName);
}
}
}
assertEquals("", sj.toString());
}
/**
* Returns the "canonical string representation" of the actions in the
* specified mask.
* Always returns present actions in the following order:
* connect, listen, accept, resolve.
*
* @param mask a specific integer action mask to translate into a string
* @return the canonical string representation of the actions
*/
private static String getActions(int mask) {
StringJoiner sj = new StringJoiner(",");
if ((mask & CONNECT) == CONNECT) {
sj.add("connect");
}
if ((mask & LISTEN) == LISTEN) {
sj.add("listen");
}
if ((mask & ACCEPT) == ACCEPT) {
sj.add("accept");
}
if ((mask & RESOLVE) == RESOLVE) {
sj.add("resolve");
}
return sj.toString();
}
public static String modifierToString(int mod) {
StringJoiner sj = new StringJoiner(" ");
if ((mod & ACC_BRIDGE) != 0) sj.add("[bridge]");
if ((mod & ACC_SYNTHETIC) != 0) sj.add("[syntetic]");
if ((mod & ACC_PUBLIC) != 0) sj.add("public");
if ((mod & ACC_PROTECTED) != 0) sj.add("protected");
if ((mod & ACC_PRIVATE) != 0) sj.add("private");
/* Canonical order */
if ((mod & ACC_ABSTRACT) != 0) sj.add("abstract");
if ((mod & ACC_STATIC) != 0) sj.add("static");
if ((mod & ACC_FINAL) != 0) sj.add("final");
if ((mod & ACC_TRANSIENT) != 0) sj.add("transient");
if ((mod & ACC_VOLATILE) != 0) sj.add("volatile");
if ((mod & ACC_SYNCHRONIZED) != 0) sj.add("synchronized");
if ((mod & ACC_NATIVE) != 0) sj.add("native");
if ((mod & ACC_STRICT) != 0) sj.add("strictfp");
if ((mod & ACC_INTERFACE) != 0) sj.add("interface");
return sj.toString();
}
/**
* Creates a string id that may be used to identify a TextClassifier result.
*/
public static String createId(
String text, int start, int end, Context context, int modelVersion,
List<Locale> locales) {
Preconditions.checkNotNull(text);
Preconditions.checkNotNull(context);
Preconditions.checkNotNull(locales);
final StringJoiner localesJoiner = new StringJoiner(",");
for (Locale locale : locales) {
localesJoiner.add(locale.toLanguageTag());
}
final String modelName = String.format(Locale.US, "%s_v%d", localesJoiner.toString(),
modelVersion);
final int hash = Objects.hash(text, start, end, context.getPackageName());
return SignatureParser.createSignature(CLASSIFIER_ID, modelName, hash);
}
@NotNull
private static String header()
{
return new StringJoiner(DELIMITER)
.add("svId")
.add("clusterId")
.add("clusterReason")
.add("fragileSiteStart")
.add("fragileSiteEnd")
.add("isFoldback")
.add("lineTypeStart")
.add("lineTypeEnd")
.add("junctionCopyNumberMin")
.add("junctionCopyNumberMax")
.add("geneStart")
.add("geneEnd")
.add("replicationTimingStart")
.add("replicationTimingEnd")
.add("localTopologyIdStart")
.add("localTopologyIdEnd")
.add("localTopologyStart")
.add("localTopologyEnd")
.add("localTICountStart")
.add("localTICountEnd")
.toString();
}
@Override
public void setName(String name) {
QueryRegenerateEvent info = this.server.getQueryInformation();
String[] names = name.split("[email protected]#");
String motd = Utils.rtrim(names[0].replace(";", "\\;"), '\\');
String subMotd = names.length > 1 ? Utils.rtrim(names[1].replace(";", "\\;"), '\\') : "";
StringJoiner joiner = new StringJoiner(";")
.add("MCPE")
.add(motd)
.add(Integer.toString(ProtocolInfo.CURRENT_PROTOCOL))
.add(ProtocolInfo.MINECRAFT_VERSION_NETWORK)
.add(Integer.toString(info.getPlayerCount()))
.add(Integer.toString(info.getMaxPlayerCount()))
.add(server.getServerUniqueId().toString())
.add(subMotd)
.add("Survival")
.add("1");
this.handler.sendOption("name", joiner.toString());
}
private void testPopLeft() {
StdOut.println("\nTest Pop Left");
Exercise33_2_Deque<String> deque = new Exercise33_2_Deque<>();
deque.pushRight("a");
deque.pushRight("b");
deque.pushRight("c");
deque.popLeft();
deque.popLeft();
StringJoiner dequeItems = new StringJoiner(" ");
for (String item : deque) {
dequeItems.add(item);
}
StdOut.println("Deque items: " + dequeItems.toString());
StdOut.println("Expected: c");
}
private File insertNewWikiContentBeforeTheLatestRelease(File releaseTrainWiki,
ProjectVersion releaseTrain, String releaseTrainName,
File releaseTrainDocFile, File releaseNotes, List<String> lines,
int lineIndex) throws IOException {
String newContent = new StringJoiner("\n")
.add(String.join("\n", lines.subList(0, lineIndex))).add("\n")
.add(new String(Files.readAllBytes(releaseNotes.toPath())))
.add(String.join("\n", lines.subList(lineIndex, lines.size())))
.toString();
Files.write(releaseTrainDocFile.toPath(), newContent.getBytes());
log.info("Successfully stored new wiki contents for release train [{}]",
releaseTrainName);
this.handler.commitAndPushChanges(releaseTrainWiki, releaseTrain);
return releaseTrainWiki;
}
private void printMissing(String variableName, TreeSet<String> tlds, ArrayType tldType) {
List<String> countryCode = Arrays.asList(DomainValidator.getTLDEntries(tldType));
StringJoiner str = new StringJoiner(",");
for (String tld : tlds) {
if (!countryCode.contains(tld)) {
str.add("\n\"" + tld + "\"");
}
}
System.out.printf("String[] " + variableName + " = new String[]{" + str.toString() + "};\n\n");
}
@Override
public String getReferenceDescription()
{
StringJoiner joiner = new StringJoiner(", ", baseSet.getReferenceDescription() + " except: [", "]");
filterSet.stream().map(CDOMReference::getReferenceDescription).forEach(joiner::add);
return joiner.toString();
}
private void printAnnotation(AnnotationElement a) {
StringJoiner sj = new StringJoiner(", ", "(", ")");
List<ValueDescriptor> vs = a.getValueDescriptors();
for (ValueDescriptor v : vs) {
Object o = a.getValue(v.getName());
if (vs.size() == 1 && v.getName().equals("value")) {
sj.add(textify(o));
} else {
sj.add(v.getName() + "=" + textify(o));
}
}
print(sj.toString());
}
private String getSubCommandNamesAsString() {
switch (getSubCommandNames().size()) {
case 0:
return "";
case 1:
return Iterables.getOnlyElement(getSubCommandNames());
default:
StringJoiner joiner = new StringJoiner("|", "<", ">");
getSubCommandNames().forEach(joiner::add);
return joiner.toString();
}
}
public void testEmptyOther() {
StringJoiner sj = new StringJoiner(",", "{", "}");
StringJoiner other = new StringJoiner(",", "[", "]");
Stream.of("a", "b", "c").forEachOrdered(sj::add);
sj.merge(other);
assertEquals(sj.toString(), "{a,b,c}");
other.setEmptyValue("EMPTY");
sj.merge(other);
assertEquals(sj.toString(), "{a,b,c}");
}
void addAlladd() {
StringJoiner sj = new StringJoiner(DASH, "{", "}");
ArrayList<String> firstOne = new ArrayList<>();
firstOne.add(ONE);
firstOne.add(TWO);
firstOne.stream().forEachOrdered(sj::add);
sj.add(THREE);
String expected = "{"+ONE+DASH+TWO+DASH+THREE+"}";
assertEquals(sj.toString(), expected);
}