下面列出了java.util.HashMap#getOrDefault ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static PerChrIntervalTree<NamedGenomicRange> loadGeneMappings(final String geneMappingFile, final int window) throws IOException, NumberFormatException, Exception {
CSVReader geneMapReader = new CSVReader(new InputStreamReader(new FileInputStream(geneMappingFile), ENCODING), '\t', '\0', 1);
String[] nextLine;
HashMap<String, ArrayList<NamedGenomicRange>> genes = new HashMap<>();
while ((nextLine = geneMapReader.readNext()) != null) {
String name = nextLine[0];
String chr = nextLine[1];
int start = Integer.valueOf(nextLine[2]);
int stop = Integer.valueOf(nextLine[3]);
ArrayList<NamedGenomicRange> chrGenes = genes.getOrDefault(chr, new ArrayList<>());
chrGenes.add(new NamedGenomicRange(name, chr, start - window < 0 ? 0 : start - window, stop + window));
genes.putIfAbsent(chr, chrGenes);
}
PerChrIntervalTree<NamedGenomicRange> geneMappings = new PerChrIntervalTree<>(NamedGenomicRange.class);
for (Map.Entry<String, ArrayList<NamedGenomicRange>> entry : genes.entrySet()) {
geneMappings.addChrElements(entry.getKey(), entry.getValue());
}
return geneMappings;
}
static void main(String[] args) {
HashMap<String, Color> colorMap = new HashMap<>();
colorMap.put("blue", Color.BLUE);
colorMap.put("violet", Color.MAGENTA);
Function<String, Color> colorFactory = name -> colorMap.getOrDefault(name, Color.BLACK);
HashMap<String, Function<Color, Vehicle>> shapeMap = new HashMap<>();
shapeMap.put("car", Car::new);
shapeMap.put("moto", Moto::new);
Function<String, Function<Color, Vehicle>> vehicleFactoryFactory =
kind -> shapeMap.getOrDefault(kind, k -> { throw new IllegalStateException("unkonwn kind " + k); });
BiFunction<String, String, Vehicle> createVehicle =
(kind, colorName) -> vehicleFactoryFactory.apply(kind).apply(colorFactory.apply(colorName));
Vehicle vehicle = createVehicle.apply("car", "violet");
System.out.println(vehicle);
}
@Test
public void testComputeState() {
HashMap<UUID, JobDefinition> jobMap = new HashMap<>();
HashMap<UUID, InstanceInfo> instanceMap = new HashMap<>();
mockState1(jobMap, instanceMap);
JobWatcherUtil.StateView v = JobWatcherUtil.computeState(jobMap, instanceMap);
HashMap<UUID, List<InstanceInfo>> jobInstances = new HashMap<>();
HashMap<UUID, UUID> instanceToJob = new HashMap<>();
for (Map.Entry<UUID, InstanceInfo> e : instanceMap.entrySet()) {
UUID jobId = e.getValue().metadata().jobDefinition();
instanceToJob.put(e.getKey(), jobId);
List<InstanceInfo> li = jobInstances.getOrDefault(jobId, new ArrayList<>());
li.add(e.getValue());
jobInstances.put(jobId, li);
}
assertEquals(jobMap, v.jobs());
assertEquals(instanceMap, v.instances());
assertEquals(instanceToJob, v.instanceToJob());
assertEquals(jobInstances, v.jobInstances());
}
static Descriptors.EnumValueDescriptor get_enum_value(PbInfoSet pbs, Descriptors.EnumDescriptor enum_desc,
Integer val) {
String name = enum_desc.getFullName();
while (!name.isEmpty() && '.' == name.charAt(0)) {
name = name.substring(1);
}
HashMap<Integer, Descriptors.EnumValueDescriptor> cache_set = pbs.enum_values_descs.getOrDefault(name, null);
if (cache_set == null) {
cache_set = new HashMap<Integer, Descriptors.EnumValueDescriptor>();
pbs.enum_values_descs.put(name, cache_set);
for (Descriptors.EnumValueDescriptor enum_val : enum_desc.getValues()) {
cache_set.put(Integer.valueOf(enum_val.getNumber()), enum_val);
}
}
return cache_set.getOrDefault(val, null);
}
private Integer getIntegerAnnotation(String annotationName, HashMap<String, Inspector> annotations, Integer defaultValue) {
if (annotations != null){
Inspector annotation = annotations.getOrDefault(annotationName, null);
if (annotation != null){
return (int)annotation.asLong();
}
}
return defaultValue;
}
private void checkSegmentStatus(HashMap<String, Long> segmentLengths, HashMap<String, Long> startOffsets,
boolean expectSealed, boolean expectDeleted, long expectedAttributeValue, StreamSegmentStore store) {
for (Map.Entry<String, Long> e : segmentLengths.entrySet()) {
String segmentName = e.getKey();
if (expectDeleted) {
AssertExtensions.assertSuppliedFutureThrows(
"Segment '" + segmentName + "' was not deleted.",
() -> store.getStreamSegmentInfo(segmentName, TIMEOUT),
ex -> ex instanceof StreamSegmentNotExistsException);
} else {
SegmentProperties sp = store.getStreamSegmentInfo(segmentName, TIMEOUT).join();
long expectedStartOffset = startOffsets.getOrDefault(segmentName, 0L);
long expectedLength = e.getValue();
Assert.assertEquals("Unexpected Start Offset for segment " + segmentName, expectedStartOffset, sp.getStartOffset());
Assert.assertEquals("Unexpected length for segment " + segmentName, expectedLength, sp.getLength());
Assert.assertEquals("Unexpected value for isSealed for segment " + segmentName, expectSealed, sp.isSealed());
Assert.assertFalse("Unexpected value for isDeleted for segment " + segmentName, sp.isDeleted());
// Check attributes.
val allAttributes = store.getAttributes(segmentName, ATTRIBUTES, true, TIMEOUT).join();
for (UUID attributeId : ATTRIBUTES) {
Assert.assertEquals("Unexpected attribute value from getAttributes().",
expectedAttributeValue, (long) allAttributes.getOrDefault(attributeId, Attributes.NULL_ATTRIBUTE_VALUE));
if (Attributes.isCoreAttribute(attributeId)) {
// Core attributes must always be available from getInfo
Assert.assertEquals("Unexpected core attribute value from getInfo().",
expectedAttributeValue, (long) sp.getAttributes().getOrDefault(attributeId, Attributes.NULL_ATTRIBUTE_VALUE));
} else {
val extAttrValue = sp.getAttributes().getOrDefault(attributeId, Attributes.NULL_ATTRIBUTE_VALUE);
Assert.assertTrue("Unexpected extended attribute value from getInfo()",
extAttrValue == Attributes.NULL_ATTRIBUTE_VALUE || extAttrValue == expectedAttributeValue);
}
}
}
}
}
private void recordAppend(String segmentName, RefCountByteArraySegment data, HashMap<String, ByteArrayOutputStream> segmentContents, ArrayList<RefCountByteArraySegment> appends) throws Exception {
ByteArrayOutputStream contents = segmentContents.getOrDefault(segmentName, null);
if (contents == null) {
contents = new ByteArrayOutputStream();
segmentContents.put(segmentName, contents);
}
data.copyTo(contents);
if (appends != null) {
appends.add(data);
}
}
@SneakyThrows(IOException.class)
private void recordAppend(String segmentName, byte[] data, HashMap<String, ByteArrayOutputStream> segmentContents) {
ByteArrayOutputStream contents = segmentContents.getOrDefault(segmentName, null);
if (contents == null) {
contents = new ByteArrayOutputStream();
segmentContents.put(segmentName, contents);
}
contents.write(data);
}
private Double getDoubleAnnotation(String annotationName, HashMap<String, Inspector> annotations, Double defaultValue) {
if (annotations != null){
Inspector annotation = annotations.getOrDefault(annotationName, null);
if (annotation != null){
return annotation.asDouble();
}
}
return defaultValue;
}
public static void main(String[] args) throws Exception {
//Cache answer...
Setup initialSetup=new Setup(new String [] {"11111","01111","00 11","00001","00000"});
Queue<Setup> queue=new ArrayDeque<>();
HashMap<String,Integer> depth=new HashMap<>();
queue.add(initialSetup);
depth.put(initialSetup.toString(),0);
while (!queue.isEmpty()) {
Setup currSetup=queue.poll();
int currDepth=depth.get(currSetup.toString());
if (currDepth<11) {
for (Setup nextSetup : currSetup.feasibleMoves()) if (!depth.containsKey(nextSetup.toString())) {
queue.offer(nextSetup);
depth.put(nextSetup.toString(),currDepth+1);
}
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCaseCount=Integer.parseInt(br.readLine());
for (int testCase=0;testCase<testCaseCount;testCase++) {
String [] s=new String [5];
for (int i=0;i<s.length;i++) {
s[i]=br.readLine();
if (s[i].length()>5) s[i]=s[i].substring(0,5);
else if (s[i].length()<5) while (s[i].length()<5) s[i]=s[i]+" ";
}
Setup finalSetup=new Setup(s);
int count=depth.getOrDefault(finalSetup.toString(),-1);
if (count==-1 || count>10) System.out.println("Unsolvable in less than 11 move(s).");
else System.out.println("Solvable in "+count+" move(s).");
}
}
/**
* @param line info line from <code>VCF</code> file
*/
public InfoField(String line) {
final HashMap<String, String> temp = VcfHeader.parseMetaLine(line, INFO_LINE_PATTERN);
VcfHeader.checkRequiredMetaKeys(temp, "ID", "Type", "Number", "Description");
mId = temp.get("ID");
mType = MetaType.parseValue(temp.get("Type"));
mNumber = new VcfNumber(temp.get("Number"));
mDescription = temp.get("Description");
mSource = temp.getOrDefault("Source", null);
mVersion = temp.getOrDefault("Version", null);
}
private ArrayList<String> mutable_configure(Map<String, HashMap<String, ArrayList<String>>> out, String[] keys) {
ArrayList<String> ret = null;
if (0 == keys.length) {
return ret;
}
HashMap<String, ArrayList<String>> first_layer = out.getOrDefault(keys[0], null);
if(first_layer == null) {
first_layer = new HashMap<String, ArrayList<String>>();
out.put(keys[0], first_layer);
}
String second_key = "";
if (keys.length > 2) {
second_key = keys[1];
for (int i = 2; i < keys.length - 1; ++ i) {
second_key += "." + keys[i];
}
}
ret = first_layer.getOrDefault(second_key, null);
if (null == ret) {
ret = new ArrayList<String>();
for (int i = 0; i < 3; ++ i) {
ret.add("");
}
first_layer.put(second_key, ret);
}
return ret;
}
public static String bfs (HashMap<String,ArrayList<String>> adjList, String src, String dest) {
Queue<String> queue=new ArrayDeque<>();
HashMap<String,String> prevNode=new HashMap<>();
queue.offer(src);
prevNode.put(src,null);
while (!queue.isEmpty()) {
String curr=queue.poll();
if (curr.equals(dest)) break;
else if (adjList.containsKey(curr)) {
for (String neighbour : adjList.get(curr)) if (!prevNode.containsKey(neighbour)) {
queue.offer(neighbour);
prevNode.put(neighbour, curr);
}
}
}
if (!prevNode.containsKey(dest)) return "";
else {
ArrayList<String> list=new ArrayList<>();
while (dest!=null) {
list.add(0,dest);
dest=prevNode.getOrDefault(dest,null);
}
StringBuilder sb=new StringBuilder();
for (String s : list) sb.append(s.charAt(0));
return sb.toString();
}
}
private static float getF1BleuScore(HashMap<NGram, Counter> sentence, int sentenceLength, HashMap<NGram, Counter> suggestion, int suggestionLength) {
int numerators[] = new int[N];
for (Map.Entry<NGram, Counter> entry : sentence.entrySet()) {
NGram ngram = entry.getKey();
int order = ngram.getOrder();
int count = entry.getValue().value;
int suggestionCount = suggestion.getOrDefault(ngram, Counter.ZERO).value;
numerators[order - 1] += Math.min(count, suggestionCount);
}
double precision = 0;
double recall = 0;
for (int order = 1; order <= N; ++order) {
precision += Math.log(smooth(numerators[order - 1], Math.max(suggestionLength - order + 1, 0), 1));
recall += Math.log(smooth(numerators[order - 1], Math.max(sentenceLength - order + 1, 0), 1));
}
precision = Math.exp(precision / N);
recall = Math.exp(recall / N);
// compute F1
return (float) (2 * (precision * recall) / (precision + recall));
}
public int[] findRightInterval(Interval[] intervals) {
HashMap<Integer, Integer> cache = new HashMap<>();
for (int i = 0; i < intervals.length; i++)
cache.put(intervals[i].start, i);
int[] result = new int[intervals.length];
for (int j = 0; j < intervals.length; j++)
result[j] = cache.getOrDefault(intervals[j].end, -1);
return result;
}
private <T> void recordAppend(T segmentIdentifier, byte[] data, HashMap<T, ByteArrayOutputStream> segmentContents) {
ByteArrayOutputStream contents = segmentContents.getOrDefault(segmentIdentifier, null);
if (contents == null) {
contents = new ByteArrayOutputStream();
segmentContents.put(segmentIdentifier, contents);
}
try {
contents.write(data);
} catch (IOException ex) {
Assert.fail(ex.toString());
}
}
private List<BlobDiff> getConflictDiff(
List<BlobDiff> diffListA,
List<BlobDiff> diffListB,
HashMap<String, List<String>> conflictLocationMap,
Map<String, BlobExpanded> locationBlobsMapParentCommitSimple)
throws ModelDBException {
List<BlobDiff> blobDiffList = new LinkedList<BlobDiff>(); // TODO sort?
HashMap<String, List<BlobDiff>> diffMapA =
getLocationMapDiff(diffListA, conflictLocationMap.keySet());
HashMap<String, List<BlobDiff>> diffMapB =
getLocationMapDiff(diffListB, conflictLocationMap.keySet());
for (Entry<String, List<String>> entry : conflictLocationMap.entrySet()) {
LOGGER.debug(entry.getKey());
LOGGER.debug(entry.getValue());
List<BlobDiff> locSpecificBlobDiffA =
diffMapA.getOrDefault(entry.getKey(), Collections.emptyList());
List<BlobDiff> locSpecificBlobDiffB =
diffMapB.getOrDefault(entry.getKey(), Collections.emptyList());
BlobExpanded parentBlobExpanded =
locationBlobsMapParentCommitSimple.getOrDefault(
entry.getKey(), BlobExpanded.newBuilder().build());
BlobDiff.Builder diffBuilder = BlobDiff.newBuilder().setStatus(DiffStatus.CONFLICTED);
if (!locSpecificBlobDiffA.isEmpty()) {
diffBuilder.addAllLocation(locSpecificBlobDiffA.get(0).getLocationList());
} else {
diffBuilder.addAllLocation(locSpecificBlobDiffB.get(0).getLocationList());
}
blobDiffList.addAll(
ConflictGenerator.setConflictBlobsInDiff(
diffBuilder.build(),
locSpecificBlobDiffA,
locSpecificBlobDiffB,
parentBlobExpanded.getBlob()));
}
return blobDiffList;
}
public RandomListNode copyRandomList(RandomListNode head) {
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode dummyHead = new RandomListNode(0), cursor = dummyHead;
while (head != null) {
cursor.next = map.getOrDefault(head, new RandomListNode(head.label));
if (head.random != null) {
cursor.next.random = map.getOrDefault(head.random, new RandomListNode(head.random.label));
map.put(head.random, cursor.next.random);
}
head = head.next;
cursor = cursor.next;
}
return dummyHead.next;
}
@SuppressWarnings("unchecked")
static public void dumpConstIntoHashMap(String package_name, HashMap<String, Object> parent,
Descriptors.Descriptor msg_desc) {
String msg_seg = msg_desc.getName();
HashMap<String, Object> msg_root = null;
Object msg_node = parent.getOrDefault(msg_seg, null);
String msg_full_name = String.format("%s.%s", package_name, msg_seg);
if (msg_node != null) {
if (msg_node instanceof HashMap) {
msg_root = (HashMap<String, Object>) msg_node;
} else {
ProgramOptions.getLoger().error("message name %s conflict.", msg_full_name);
return;
}
}
// enum in message.
for (Descriptors.EnumDescriptor enum_desc : msg_desc.getEnumTypes()) {
if (null == msg_root) {
msg_root = new HashMap<String, Object>();
parent.put(msg_seg, msg_root);
}
dumpConstIntoHashMap(msg_full_name, msg_root, enum_desc);
}
// if has oneof in message, dump all fields's number.
for (Descriptors.OneofDescriptor oneof_desc : msg_desc.getOneofs()) {
if (oneof_desc.getFieldCount() <= 0) {
continue;
}
if (null == msg_root) {
msg_root = new HashMap<String, Object>();
parent.put(msg_seg, msg_root);
}
dumpConstIntoHashMap(msg_full_name, msg_root, oneof_desc);
}
// nested message
for (Descriptors.Descriptor sub_msg_desc : msg_desc.getNestedTypes()) {
if (null == msg_root) {
msg_root = new HashMap<String, Object>();
parent.put(msg_seg, msg_root);
}
dumpConstIntoHashMap(msg_full_name, msg_root, sub_msg_desc);
}
}
public static void main (String [] args) throws Exception {
String [] notes= {"C","C#","D","D#","E","F","F#","G","G#","A","A#","B","C","C#","D","D#","E","F","F#","G","G#","C","C#","D","D#","E","F","F#","G","G#"};
HashMap<String, String> extraNameLookup=new HashMap<>();
extraNameLookup.put("AB", "G#");
extraNameLookup.put("BB", "A#");
extraNameLookup.put("CB", "B");
extraNameLookup.put("DB", "C#");
extraNameLookup.put("EB", "D#");
extraNameLookup.put("FB", "E");
extraNameLookup.put("GB", "F#");
extraNameLookup.put("B#", "C");
extraNameLookup.put("E#", "F");
int [][] testCombination= {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}};
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s=br.readLine())!=null) {
StringTokenizer st=new StringTokenizer(s);
String n1=st.nextToken();
String n2=st.nextToken();
String n3=st.nextToken();
String n1Real=extraNameLookup.getOrDefault(n1.toUpperCase(), n1.toUpperCase());
String n2Real=extraNameLookup.getOrDefault(n2.toUpperCase(), n2.toUpperCase());
String n3Real=extraNameLookup.getOrDefault(n3.toUpperCase(), n3.toUpperCase());
String ans="";
String [] str= {n1Real,n2Real,n3Real};
int lowestIndex=88;
for (int [] comb : testCombination) {
//Find different arrangement of keys.
int index1=indexOf(notes,0,str[comb[0]]);
if (index1==-1) continue;
int index2=indexOf(notes,index1,str[comb[1]]);
if (index2==-1) continue;
int index3=indexOf(notes,index2,str[comb[2]]);
if (index3==-1) continue;
int delta1=index2-index1, delta2=index3-index2;
if (delta1==4 && delta2==3 && index1<lowestIndex) { //Ensure we have the lowest key.
ans="a "+str[comb[0]].toUpperCase()+" Major chord";
lowestIndex=index1;
}
else if (delta1==3 && delta2==4 && index1<lowestIndex) {
ans="a "+str[comb[0]].toUpperCase()+" Minor chord";
lowestIndex=index1;
}
if (ans.length()>0) break;
}
if (ans.length()==0) ans="unrecognized";
System.out.printf("%s %s %s is %s.\n", n1, n2, n3, ans);
}
}