错误结果在Java中的Collectors.groupingBy

时间:2018-10-03 10:49:38

标签: java arrays collectors

我有file.txt,我想通过ip将数据分组,我正在使用Collectors.groupingBy

文件数据

333.000.000,Newyork,50
200.000.000,china,200
333.000.000,brazil,150
444.000.000,japon,40
200.000.000,icland,400

我使用Collectors.groupingBy对数据进行分组,因此我需要显示以下结果:

333.000.000=[Newyork,brazil]
200.000.000=[china,icland]
444.000.000=[japon]

探针显示如下:

333.000.000=[class_ip@5b6f7412,class_ip@8b6f7412]
200.000.000=[class_ip@312b1dae,class_ip@6b7f7412]
444.000.000=[class_ip@7530d0]

我的代码

class class_ip{
    private String ip;
    private String title;
    public class_ip(String ip,String title) {
        this.ip = ip;        
        this.title = title;
    }
    public String getIP() {return ip;}
    public String getTitle() {return title;}

    public void setTitle(String title) { this.title = title;}
    public void setIP(String ip) { this.ip = ip;}

    public String getAll() {
        return ip+","+title;
    }
} 

     List<class_ip> array_ip = new ArrayList<>();

    // read data from file
    while ((strLine = br.readLine()) != null)   {
                array_ip.add(new class_ip(ip,title));
    }

   Map<String,List<class_ip>> groupByIP = new HashMap<>();
   groupByIP =array_ip.stream().collect(Collectors.groupingBy(class_ip::getIP)); 

   System.out.println(groupByIP);

2 个答案:

答案 0 :(得分:3)

class_ip@312b1dae由默认的Object#toString()撤消,您需要在class_ip中覆盖它,例如:

@Override
public String toString() {
    return getTitle();
}

答案 1 :(得分:2)

如果要显示标题而不是update mytable t set orderid = (select count(*) from mytable t2 where t2.a > t.a or (t2.a = t.a and t2.b >= t.b) ); 实例,请使用class_ip并生成Collectors.mapping

Map<String,List<String>>