基于多个元素类别对大型列表进行排序或分离

时间:2017-08-07 14:17:04

标签: java sorting data-structures

我有一个大约一千个元素的大型ArrayList。这些元素是用于测试的FlashCards。那些FlashCards都属于13个不同的类别之一。如何根据类别将此大型集合拆分为不同的单个列表?

2 个答案:

答案 0 :(得分:3)

假设您有一个FlashCard类,并使用getCategory()方法,您可以使用流来收集和分组这些...

// Given a list of FlashCard objects
final List<FlashCard> cards = ...

// Convert to stream, and collect them by category. 
final Map<String, List<FlashCard>> byCategory = cards.stream()
            .collect(Collectors.groupingBy(FlashCard::getCategory));

地图现在将类别作为关键字,并在列表中将该类别中的每个FlashCard表示。

答案 1 :(得分:0)

假设您的闪存卡具有属性Type,如

class FlashCard {
    private Type myType;
    private String name;

    @Override
    public String toString() {
        return "MyDevice [myType=" + myType + ", name=" + name + "]";
    }

    public FlashCard(Type myType, String name) {
        this.myType = myType;
        this.name = name;
    }

    public Type getMyType() {
        return myType;
    }

    public void setMyType(Type myType) {
        this.myType = myType;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

enum Type {
    ONE, TWO, NONE
}

然后你可以将它们映射为:

List<FlashCard> lisOfDevices = new ArrayList<>();
lisOfDevices.add(new FlashCard(Type.ONE, UUID.randomUUID().toString().substring(0, 4)));
lisOfDevices.add(new FlashCard(Type.ONE, UUID.randomUUID().toString().substring(0, 4)));
lisOfDevices.add(new FlashCard(Type.TWO, UUID.randomUUID().toString().substring(0, 4)));
lisOfDevices.add(new FlashCard(Type.ONE, UUID.randomUUID().toString().substring(0, 4)));
lisOfDevices.add(new FlashCard(Type.ONE, UUID.randomUUID().toString().substring(0, 4)));
lisOfDevices.add(new FlashCard(Type.TWO, UUID.randomUUID().toString().substring(0, 4)));
lisOfDevices.add(new FlashCard(Type.TWO, UUID.randomUUID().toString().substring(0, 4)));
lisOfDevices.add(new FlashCard(Type.NONE, UUID.randomUUID().toString().substring(0, 4)));
lisOfDevices.add(new FlashCard(Type.NONE, UUID.randomUUID().toString().substring(0, 4)));

Map<Type, List<FlashCard>> categoryMap = new HashMap<>();
lisOfDevices.stream().map(FlashCard::getMyType).distinct().forEach(id -> categoryMap.put(id,
        lisOfDevices.stream().filter(object -> id.equals(object.getMyType())).collect(Collectors.toList())));

// print it
System.out.println(categoryMap.size());
System.out.println(categoryMap);