在Java中将多个字符串分组为通用字符串

时间:2012-02-08 21:36:27

标签: java string grouping

我必须将多个字符串组合成一个进行比较。这个分组应该完全像Java OO范例:一个“描述”子字符串的字符串。 例如:

String one = "hammer";
String two = "screwdriver";
String three = "pliers";

现在让我们说你要“描述”它们:

String str = "tool"

上面的所有字符串都是工具。现在,我的代码有一个,两个,三个字符串,并将它们更改为“工具”。因此,例如,字符串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";
}

也许这是一个愚蠢的事情,但现在我没有任何想法!谢谢!

编辑:我的团队有限,我知道我只有猫,狗,马,锤等...... edit2:很难表达我的意思!它应该是这样的:

Group Animal = {cat, dog, horse}
Group Tools = {hammer, screwdriver}

// methods to recognize to wich one of the two groups is categorizable

Map是一个好主意,但必须在每个运行时填充。是不是有一些静态的东西,比如把它们直接写成大括号?它应该像枚举,但从未使用过!

4 个答案:

答案 0 :(得分:6)

我开始这样的事情。

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);
    }
}

然后,

Category tools = new Category("tool");
tools.add("hammer", "screwdriver", "pliers");

Category animals = new Category("animal");
animals.add("horse", "dog", "cat");

最后,

// 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";
}

答案 1 :(得分:1)

使用Map<String, String>,其中地图的键是您的6个字符串,值为"animal""tool"。使用map.get(str)获取字符串的类型。

答案 2 :(得分:1)

Map映射字符串构建到其“类别”。

Map<String, String> category = new HashMap<String, String>();
category.put("hammer", "tool");
category.put("screwdriver", "tool");
category.put("horse", "animal");

然后您只需使用category.get(str)来获取该类别。

如果它们是静态的,那么最好由番石榴ImmutableMap提供服务,可能使用它的构建器语法。

答案 3 :(得分:1)

有很多方法可以让这只猫(npi;) - 这是一种方法。注释是另一种方法。(例如,Category是一种具有目标类型字段的注释类型等。)显然,比较机制不是在下面完成的,但这是微不足道的。

public enum Category {
    animal, tool
}
public interface Categorized {
    Category getCategory();
}
public enum FarmAnimals implements Categorized {
    dog, cat, horse, rabbit;
    public Category getCategory() {
        return Category.animal;
    }
}
public enum GarageTools implements Categorized {
    screwdriver, drill, wrench;
    public Category getCategory() {
        return Category.tool;
    }
}

[编辑:当然,如果你需要嵌入式空间等,你的枚举可以是形式狗(“狗”)等。]