对列表中的数据进行分类

时间:2013-05-11 22:56:48

标签: java algorithm sorting

我在这里有一个列表:

List<String> container = new ArrayList<String>();
container.add("Book");
container.add("Paper");
container.add("Book");
container.add("Pen");
container.add("Pen");
container.add("Book");

如何将此列表中的数据分类为3个子列表,如下所示:

List <String> container1  ==>that still keep 3 elements which have the same name "Book"
List <String> container2  ==>that have 1 element which is "Paper"
List <String> container3  ==>that still keep 2 elements which have the same name "Pen"

感谢您的帮助

如果有很多评论我的问题不清楚,那么我会这样问这个

如果我的列表中包含的元素多于上面的示例列表,则容器列表如container1,container2 ...,containerN将生成取决于重复元素的数量

我该怎么做?

2 个答案:

答案 0 :(得分:3)

如果您不介意详细程度,那么您可以使用Google Guava的FluentIterable。这将允许您在给定特定Predicate的情况下过滤集合。

List<String> words = Lists
        .newArrayList("Book", "Paper", "Book", "Pen", "Paper", "Book");

FluentIterable<String> bookFiltered = FluentIterable
        .from(words)
        .filter(new Predicate<String>() {
    @Override
    public boolean apply(final String input) {
        return "Book".equals(input);
    }
});

FluentIterable<String> paperFiltered = FluentIterable
        .from(words)
        .filter(new Predicate<String>() {
    @Override
    public boolean apply(final String input) {
        return "Paper".equals(input);
    }
});

FluentIterable<String> penFiltered = FluentIterable
        .from(words)
        .filter(new Predicate<String>() {
    @Override
    public boolean apply(final String input) {
        return "Pen".equals(input);
    }
});

System.out.println(bookFiltered); // [Book, Book, Book]
System.out.println(paperFiltered); // [Paper, Paper]
System.out.println(penFiltered); // [Pen]

答案 1 :(得分:3)

这是一个通用的working implementation,可以为任意数量的重复元素执行所需的操作,以及正确覆盖hashCodeequals的任何类型的集合(例如,Integer) ,String,Double):

public <T> Collection<List<T>> classify(Collection<T> container) {
    Map<T, List<T>> lists = new HashMap<>();
    for (T element : container) {
        List<T> elementList = lists.get(element);
        if (elementList == null) {
            elementList = new ArrayList<>();
            lists.put(element, elementList);
        }
        elementList.add(element);
    } 
    return lists.values();
 }

样本用法:

Collection<List<String>> lists = classify(container);
System.out.println(lists);