Ang*_*elo 0 java string grouping
我必须将多个字符串组合成一个来进行比较.这个分组应该完全像Java OO范例:一个"描述"子字符串的字符串.例:
String one = "hammer";
String two = "screwdriver";
String three = "pliers";
Run Code Online (Sandbox Code Playgroud)
现在让我们说你要"描述"它们:
String str = "tool"
Run Code Online (Sandbox Code Playgroud)
上面的所有字符串都是工具 现在,我的代码有一个,两个,三个字符串,并将它们更改为"工具".因此,例如,字符串1成为工具,字符串2和字符串3相同.如何"分类"他们?另一个扩展示例:
String one = "hammer"
String two = "screwdriver";
String three = "pliers";
String four = "horse";
String five = "cat";
String six = "dog";
public void stringConverter(String str)
{
if ("string match to an animal")
str = "animal";
if ("string match to a tool")
str = "tool";
}
Run Code Online (Sandbox Code Playgroud)
也许这是一个愚蠢的事情,但现在我没有任何想法!谢谢!
编辑:我的团队是有限的,我知道我只有猫,狗,马,锤等...编辑2:很难表达我!它应该是这样的:
Group Animal = {cat, dog, horse}
Group Tools = {hammer, screwdriver}
// methods to recognize to wich one of the two groups is categorizable
Run Code Online (Sandbox Code Playgroud)
Map是一个好主意,但必须在每个运行时填充.是不是有一些静态的东西,比如把它们直接写成大括号?它应该像枚举,但以前从未使用过!
我会开始这样的事情.
public class Category
{
private final String name;
private final Set<String> items;
public Category(String name)
{
this.name = name;
this.items = new HashSet<String>();
}
public String getName()
{
return name;
}
public void add(String... items)
{
for (String item : items)
{
this.items.add(item);
}
}
public boolean contains(String item)
{
return this.items.contains(item);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,
Category tools = new Category("tool");
tools.add("hammer", "screwdriver", "pliers");
Category animals = new Category("animal");
animals.add("horse", "dog", "cat");
Run Code Online (Sandbox Code Playgroud)
最后,
// Guava for brevity
List<Category> categories = Lists.newArrayList(tools, animals);
public void stringConverter(String str)
{
for (Category c : categories)
{
if (c.contains(str)) return c.getName();
}
return "not found";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
998 次 |
| 最近记录: |