下面列出了java.util.Map#ofEntries ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Map<String, Object> summarizePortfolioStructure(final PortfolioOverview portfolioOverview) {
return Map.ofEntries(
entry("absoluteShare", moneyPerRating(portfolioOverview::getInvested)),
entry("relativeShare", numberPerRating(portfolioOverview::getShareOnInvestment)),
entry("total", portfolioOverview.getInvested()
.getValue()),
entry("profitability", portfolioOverview.getAnnualProfitability()),
entry("monthlyProfit", portfolioOverview.getMonthlyProfit()
.getValue()),
entry("minimalProfitability", portfolioOverview.getMinimalAnnualProfitability()),
entry("minimalMonthlyProfit", portfolioOverview.getMinimalMonthlyProfit()
.getValue()),
entry("optimalProfitability", portfolioOverview.getOptimalAnnualProfitability()),
entry("optimalMonthlyProfit", portfolioOverview.getOptimalMonthlyProfit()
.getValue()),
entry("timestamp", toDate(portfolioOverview.getTimestamp())));
}
@Override
public void testGetPolicyJsonReplacementsNoDynamodb() {
String storageLocationBaseStr = "bucket/cluster";
String bucket = "bucket";
Map<String, String> expectedPolicyJsonReplacements = Map.ofEntries(
Map.entry("${STORAGE_LOCATION_BASE}", storageLocationBaseStr),
Map.entry("${DATALAKE_BUCKET}", bucket),
Map.entry("${DYNAMODB_TABLE_NAME}", "")
);
StorageLocationBase storageLocationBase = new StorageLocationBase();
storageLocationBase.setValue(storageLocationBaseStr);
CloudS3View cloudFileSystem = new CloudS3View(CloudIdentityType.ID_BROKER);
Map<String, String> policyJsonReplacements = awsRangerAuditRolePermissionValidator
.getPolicyJsonReplacements(storageLocationBase,
cloudFileSystem);
assertThat(policyJsonReplacements).isEqualTo(expectedPolicyJsonReplacements);
}
@Override
public Map<String, URL> getImages()
{
return Map.ofEntries(
entry("comment", ScanSystem.class.getResource("/icons/comment.gif")),
entry("config_log", ScanSystem.class.getResource("/icons/configcommand.gif")),
entry("delay", ScanSystem.class.getResource("/icons/delaycommand.gif")),
entry("if", ScanSystem.class.getResource("/icons/ifcommand.gif")),
entry("include", ScanSystem.class.getResource("/icons/includecommand.gif")),
entry("log", ScanSystem.class.getResource("/icons/logcommand.gif")),
entry("loop", ScanSystem.class.getResource("/icons/loopcommand.gif")),
entry("parallel", ScanSystem.class.getResource("/icons/parallelcommand.gif")),
entry("script", ScanSystem.class.getResource("/icons/scriptcommand.gif")),
entry("sequence", ScanSystem.class.getResource("/icons/sequencecommand.gif")),
entry("set", ScanSystem.class.getResource("/icons/setcommand.gif")),
entry("wait", ScanSystem.class.getResource("/icons/waitcommand.gif"))
);
}
private static void createCollections() {
System.out.println("CREATING COLLECTIONS");
List<String> list = List.of("a", "b", "c");
Set<String> set = Set.of("a", "b", "c");
Map<String, Integer> mapImmediate = Map.of(
"one", 1,
"two", 2,
"three", 3);
Map<String, Integer> mapEntries = Map.ofEntries(
entry("one", 1),
entry("two", 2),
entry("three", 3));
Stream.of(list, set, mapImmediate.entrySet(), mapEntries.entrySet())
.map(CollectionFactories::joinElementsToString)
.forEach(System.out::print);
System.out.println();
}
private Configuration(List<Configuration> parents, Resolver resolver) {
Map<ResolvedModule, Set<ResolvedModule>> g = resolver.finish(this);
@SuppressWarnings(value = {"rawtypes", "unchecked"})
Entry<String, ResolvedModule>[] nameEntries
= (Entry<String, ResolvedModule>[])new Entry[g.size()];
ResolvedModule[] moduleArray = new ResolvedModule[g.size()];
int i = 0;
for (ResolvedModule resolvedModule : g.keySet()) {
moduleArray[i] = resolvedModule;
nameEntries[i] = Map.entry(resolvedModule.name(), resolvedModule);
i++;
}
this.parents = List.copyOf(parents);
this.graph = g;
this.modules = Set.of(moduleArray);
this.nameToModule = Map.ofEntries(nameEntries);
this.targetPlatform = resolver.targetPlatform();
}
public static Map<String, Object> getLoanData(final Loan loan) {
return Map.ofEntries(
entry("loanId", loan.getId()),
entry("loanAmount", loan.getAmount()
.getValue()),
entry("loanAnnuity", loan.getAnnuity()
.getValue()),
entry("loanInterestRate", loan.getRating()
.getCode()),
entry("loanRating", loan.getRating()),
entry("loanTerm", loan.getTermInMonths()),
entry("loanUrl", loan.getUrl()),
entry("loanRegion", loan.getRegion()),
entry("loanMainIncomeType", loan.getMainIncomeType()),
entry("loanPurpose", loan.getPurpose()),
entry("loanName", loan.getName()),
entry("insurance", loan.isInsuranceActive()));
}
@Override
public void testGetPolicyJsonReplacements() {
String storageLocationBaseStr = "bucket/cluster";
String bucket = "bucket";
String dynamodbTableName = "tableName";
Map<String, String> expectedPolicyJsonReplacements = Map.ofEntries(
Map.entry("${STORAGE_LOCATION_BASE}", storageLocationBaseStr),
Map.entry("${DATALAKE_BUCKET}", bucket),
Map.entry("${DYNAMODB_TABLE_NAME}", dynamodbTableName)
);
StorageLocationBase storageLocationBase = new StorageLocationBase();
storageLocationBase.setValue(storageLocationBaseStr);
CloudS3View cloudFileSystem = new CloudS3View(CloudIdentityType.ID_BROKER);
cloudFileSystem.setS3GuardDynamoTableName(dynamodbTableName);
Map<String, String> policyJsonReplacements = awsDataAccessRolePermissionValidator
.getPolicyJsonReplacements(storageLocationBase,
cloudFileSystem);
assertThat(policyJsonReplacements).isEqualTo(expectedPolicyJsonReplacements);
}
@Override
protected Map<String, Supplier<?>> createAccessors() {
return Map.ofEntries(
Map.entry("id", () -> member.getUser().getId()),
Map.entry("mention", member::getAsMention),
Map.entry("nickname", member::getEffectiveName),
Map.entry("name", () -> member.getUser().getName()),
Map.entry("discriminator", () -> member.getUser().getDiscriminator()),
Map.entry("joinedAt", () -> DateTimePlaceholderResolver.of(member.getTimeJoined(), locale, member.getGuild(), context)),
Map.entry("createdAt", () -> DateTimePlaceholderResolver.of(member.getUser().getTimeCreated(), locale, member.getGuild(), context)),
Map.entry("status", () -> context.getBean(MessageService.class).getEnumTitle(member.getOnlineStatus())),
Map.entry("avatarUrl", () -> member.getUser().getEffectiveAvatarUrl()),
Map.entry("level", () -> getRankingInfo().getLevel()),
Map.entry("cookies", () -> getRankingInfo().getCookies()),
Map.entry("voiceTime", () -> CommonUtils.formatDuration(getRankingInfo().getVoiceActivity())));
}
@Override
public void testGetPolicyJsonReplacements() {
String storageLocationBaseStr = "bucket/cluster";
String bucket = "bucket";
String dynamodbTableName = "tableName";
Map<String, String> expectedPolicyJsonReplacements = Map.ofEntries(
Map.entry("${STORAGE_LOCATION_BASE}", storageLocationBaseStr),
Map.entry("${DATALAKE_BUCKET}", bucket),
Map.entry("${DYNAMODB_TABLE_NAME}", dynamodbTableName)
);
StorageLocationBase storageLocationBase = new StorageLocationBase();
storageLocationBase.setValue(storageLocationBaseStr);
CloudS3View cloudFileSystem = new CloudS3View(CloudIdentityType.ID_BROKER);
cloudFileSystem.setS3GuardDynamoTableName(dynamodbTableName);
Map<String, String> policyJsonReplacements = awsRangerAuditRolePermissionValidator
.getPolicyJsonReplacements(storageLocationBase,
cloudFileSystem);
assertThat(policyJsonReplacements).isEqualTo(expectedPolicyJsonReplacements);
}
private void testTransform(Entry<String, String> source)
{
Entry<String, String> columns = Map.entry(COLUMNS, "column_code=$.superCodes..code;"
+ "column_codeSystem=$.superCodes..codeSystem;column_type=$.superCodes..type");
Map<String, String> keyToJsonPathValue = Map.ofEntries(columns, source);
String expectedTable = "|column_code|column_codeSystem|column_type|\n|107214|VIVIDUS|A|\n|107224|VIVIDUS|B|"
+ "\n|107314|VIVIDUS|C|\n|107324|VIVIDUS|D|\n|107XX4|VIVIDUS|E|\n|1|true|F|";
String table = jsonTableGenerator.transform(StringUtils.EMPTY, null, createProperties(keyToJsonPathValue));
assertEquals(expectedTable, table);
}
public static void main(String[] args) {
// 空列表,数据类型为 Object
List immutableList = List.of();
// 创建 List<String>
var foo = List.of("biezhi", "github", "王爵的技术小黑屋");
// 空 Map,Key 和 Value 类型都是 Object
Map emptyImmutableMap = Map.of();
// 快速创建一个 Map
var mmp = Map.of(2017, "先赚他一个亿", 2018, "去年的梦想可能有点儿夸张");
// 使用 Entries 创建一个 Map
Map<Integer, String> emptyEntryMap = Map.ofEntries(
entry(20, "装逼"),
entry(30, "单身"),
entry(40, "回家种地")
);
// 创建一个 Map.Entry
Map.Entry<String, String> immutableMapEntry = Map.entry("biezhi", "emmmm");
// 其实和上面的代码片段是一样一样的
Map.ofEntries(immutableMapEntry);
// 创建一个空 Set<String>
Set<String> immutableSet = Set.of();
// 快速创建一个 Set<String>
Set<String> bar = Set.of("我", "可能", "是个", "假的", "程序员");
}
public static Map<String, Object> getSellInfoData(final SellInfo sellInfo) {
return Map.ofEntries(
entry("currentDaysDue", sellInfo.getLoanHealthStats()
.getCurrentDaysDue()),
entry("daysSinceLastDue", sellInfo.getLoanHealthStats()
.getDaysSinceLastInDue()),
entry("longestDaysDue", sellInfo.getLoanHealthStats()
.getLongestDaysDue()));
}
@SuppressWarnings({ "unchecked", "rawtypes", "nls" })
@Override
public <TWP, TW> Map<WidgetDescriptor, WidgetRepresentationFactory<TWP, TW>> getWidgetRepresentationFactories()
{
final WidgetDescriptor unknown_widget = new WidgetDescriptor(WidgetRepresentationFactory.UNKNOWN, null, WidgetRepresentationFactory.UNKNOWN, null, "Unknown Widget")
{
@Override
public Widget createWidget()
{
// Cannot create instance
return null;
}
};
return Map.ofEntries(
entry(ActionButtonWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ActionButtonRepresentation()),
entry(ArcWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ArcRepresentation()),
entry(ArrayWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ArrayRepresentation()),
entry(BoolButtonWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new BoolButtonRepresentation()),
entry(ByteMonitorWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ByteMonitorRepresentation()),
entry(CheckBoxWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new CheckBoxRepresentation()),
entry(ChoiceButtonWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ChoiceButtonRepresentation()),
entry(ComboWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ComboRepresentation()),
entry(DataBrowserWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new DataBrowserRepresentation()),
entry(EmbeddedDisplayWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new EmbeddedDisplayRepresentation()),
entry(EllipseWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new EllipseRepresentation()),
entry(FileSelectorWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new FileSelectorRepresentation()),
entry(GroupWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new GroupRepresentation()),
entry(ImageWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ImageRepresentation()),
entry(LabelWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new LabelRepresentation()),
entry(LEDWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new LEDRepresentation()),
entry(MeterWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new MeterRepresentation()),
entry(MultiStateLEDWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new MultiStateLEDRepresentation()),
entry(NavigationTabsWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new NavigationTabsRepresentation()),
entry(PictureWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new PictureRepresentation()),
entry(PolygonWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new PolygonRepresentation()),
entry(PolylineWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new PolylineRepresentation()),
entry(ProgressBarWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ProgressBarRepresentation()),
entry(RadioWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new RadioRepresentation()),
entry(RectangleWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new RectangleRepresentation()),
entry(ScaledSliderWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ScaledSliderRepresentation()),
entry(ScrollBarWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ScrollBarRepresentation()),
entry(SlideButtonWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new SlideButtonRepresentation()),
entry(SpinnerWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new SpinnerRepresentation()),
entry(StripchartWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new StripchartRepresentation()),
entry(SymbolWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new SymbolRepresentation()),
entry(TableWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new TableRepresentation()),
entry(TabsWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new TabsRepresentation()),
entry(TankWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new TankRepresentation()),
entry(TextEntryWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new TextEntryRepresentation()),
entry(TextSymbolWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new TextSymbolRepresentation()),
entry(TextUpdateWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new TextUpdateRepresentation()),
entry(ThermometerWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new ThermometerRepresentation()),
entry(Viewer3dWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new Viewer3dRepresentation()),
entry(WebBrowserWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new WebBrowserRepresentation()),
entry(XYPlotWidget.WIDGET_DESCRIPTOR, () -> (WidgetRepresentation) new XYPlotRepresentation()),
entry(unknown_widget, () -> (WidgetRepresentation) new UnknownRepresentation()));
}
public static void saveAndRemoveProperties(Properties props) {
if (initLevel() != 0)
throw new IllegalStateException("Wrong init level");
@SuppressWarnings({"rawtypes", "unchecked"})
Map<String, String> sp =
Map.ofEntries(props.entrySet().toArray(new Map.Entry[0]));
// only main thread is running at this time, so savedProps and
// its content will be correctly published to threads started later
savedProps = sp;
// Set the maximum amount of direct memory. This value is controlled
// by the vm option -XX:MaxDirectMemorySize=<size>.
// The maximum amount of allocatable direct buffer memory (in bytes)
// from the system property sun.nio.MaxDirectMemorySize set by the VM.
// The system property will be removed.
String s = (String)props.remove("sun.nio.MaxDirectMemorySize");
if (s != null) {
if (s.equals("-1")) {
// -XX:MaxDirectMemorySize not given, take default
directMemory = Runtime.getRuntime().maxMemory();
} else {
long l = Long.parseLong(s);
if (l > -1)
directMemory = l;
}
}
// Check if direct buffers should be page aligned
s = (String)props.remove("sun.nio.PageAlignDirectMemory");
if ("true".equals(s))
pageAlignDirectMemory = true;
// Remove other private system properties
// used by java.lang.Integer.IntegerCache
props.remove("java.lang.Integer.IntegerCache.high");
// used by sun.launcher.LauncherHelper
props.remove("sun.java.launcher.diag");
// used by jdk.internal.loader.ClassLoaders
props.remove("jdk.boot.class.path.append");
}
@Test(expectedExceptions=IllegalArgumentException.class)
public void dupKeysDisallowedN() {
Map.Entry<Integer,String>[] entries = genEntries(MAX_ENTRIES);
entries[MAX_ENTRIES-1] = Map.entry(0, "xxx");
Map<Integer, String> map = Map.ofEntries(entries);
}
private Map<String, String> getGroupMappings(String adminGroupName) {
return Map.ofEntries(
Map.entry(adminGroupName, FIXED_MANAGED_IDENTITY)
);
}
@Test(expectedExceptions=NullPointerException.class)
public void nullEntryDisallowedN() {
Map.Entry<Integer,String>[] entries = genEntries(MAX_ENTRIES);
entries[5] = null;
Map<Integer, String> map = Map.ofEntries(entries);
}
@Override
public Map<String, String> getProperties() {
return Map.ofEntries(
Map.entry("com.sun.management.jmxremote", Boolean.toString(jmxEnabled)));
}
@Override
protected Map<String, Object> getData(final WeeklySummaryEvent event) {
final ExtendedPortfolioOverview summary = event.getPortfolioOverview();
return Map.ofEntries(
entry("portfolio", Util.summarizePortfolioStructure(summary)));
}
public static void main(String[] args) {
final List<String> names = List.of("Mike", "Duke", "Paul");
final Map<Integer, String> user = Map.of(1, "Mike", 2, "Duke");
final Map<Integer, String> admins = Map.ofEntries(Map.entry(1, "Tom"), Map.entry(2, "Paul"));
final Set<String> server = Set.of("WildFly", "Open Liberty", "Payara", "TomEE");
// names.add("Tom"); throws java.lang.UnsupportedOperationException -> unmodifiable collection is created
}