如何分割Set <e>?

时间:2018-11-17 11:57:50

标签: java file set

我上了笔记本电脑课。在这个类中,我有3个参数“ String name,Integer screen,Integer price”,我创建了Set,现在如果价格超过2000 $,则需要​​分割它并与price比较,如果较低则写入第二个文件。 这是我的方法:

public void check(Set<Laptops> laptops, File under2000, File over2000){
    try{
        String under2000 = "2000";
        OutputStream under = new FileOutputStream(under2000);
        PrintStream printStream = new PrintStream(under);
        Iterator<Laptops> lap = laptops.iterator();
        while (lap.hasNext()){
            lap.next();
            if (laptops.contains(under2000)) {
                printStream.print(lap);
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

用流分割集合很容易:

    Set<Laptops> over2000 = laptops.stream().filter(l -> l.getPrice() > 2000).collect(Collectors.toSet());
    Set<Laptops> rest = new HashSet<>(laptops);
    rest.removeAll(over2000);

第一部分过滤了所有价格超过2000的笔记本电脑。其余部分将保留原始设置并删除这些笔记本电脑。比起您可以随意处理的每个集合而言。

答案 1 :(得分:-1)

public void check(Set<Laptops> laptops, File under2000file, File over2000file){
    try {
        PrintStream under2000 = new PrintStream(under2000file);
        PrintStream over2000 = new PrintStream(over2000file);
        for(Laptop laptop: laptops) {
           if(laptop.getPrice() < 2000) {
               under2000.println(laptop);
           } else {
               over2000.println(laptop);
           }
        }
        under2000.close();
        over2000.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}