[英]Printing out a TreeMap<String, TreeSet<String>> Key and Mapped Values
I have a TreeMap <String, TreeSet <String>>
{Heat = [Bosh, Lebron, Wade], Nets =[DWill, KG], Sonics = null, Warriors = [Curry,Iggy,Thompson]}
and I want to print out. 我想要打印出来。
Heat Bosh Lebron Wade
Nets DWill KG
Sonics
Warriors Curry Iggy Thompson
I've tried 我试过了
for ( String w : listNBA){
System.out.print( w + " ");
if (treemap.containsKey(w))
System.out.println(treemap.get(w));
else
System.out.println( "" ); // print nothing if team doesn't exist
But this isn't quite right either, and it's output is... 但这也不太正确,它的输出是...
Heat [Bosh, Lebron, Wade]
Nets [DWill, KG]
Sonics null
Warriors [Curry,Iggy,Thompson]
So, my question is: Is there any easy way to convert a TreeSet to a String in my print method? 所以,我的问题是:在我的print方法中有没有简单的方法将TreeSet转换为String?
You can do something like this : 你可以这样做:
StringBuilder stringBuilder = new StringBuilder();
for (Entry<String, TreeSet<String>> mapEntry : treemap.entrySet()) {
stringBuilder.append(mapEntry.getKey());
if (mapEntry.getValue() != null) {
for (String setEntry : mapEntry.getValue()) {
stringBuilder.append(" ").append(setEntry);
}
}
stringBuilder.append("\n");
}
System.out.println(stringBuilder.toString());
Java 8 has a String.join
method that works great for this: Java 8有一个
String.join
方法,适用于此:
for ( String w : listNBA){
System.out.print( w + " ");
if (treemap.containsKey(w) && treemap.get(w) != null)
System.out.println(String.join(" ",treemap.get(w)));
else
System.out.println( "" ); // print nothing if team doesn't exist
}
Note that while your original System.out.println(treemap.get(w))
printed out null
if the get
method returned null
, String.join
will throw a NullPointerException
if it gets a null parameter. 请注意,你原来
System.out.println(treemap.get(w))
打印出null
当get
方法返回null
, String.join
将抛出一个NullPointerException
,如果它得到一个空参数。 Thus, I've added a null check to the previous if
. 因此,我在前面的
if
添加了一个空检查。
join
's first parameter is a string that will be inserted between each input string. join
的第一个参数是一个字符串,它将插入每个输入字符串之间。 It can either take a variable number of String
(or any other CharSequence
) arguments, or an array of String
(or other CharSequence
). 它可以采用可变数量的
String
(或任何其他CharSequence
)参数,也可以采用String
数组(或其他CharSequence
)。
You can iterate through the entry set and print out the key and the corresponsing value. 您可以遍历条目集并打印出密钥和相应的值。
for(Map.Entry<String, TreeSet <String>> entry : treemap.entrySet())
{
System.out.print( entry.getKey() + " ");
System.out.print( entry.getValue());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.