我有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);
最佳答案
如果要显示标题而不是class_ip
实例,请使用Collectors.mapping
并生成Map<String,List<String>>
:
Map<String,List<String>> groupByIP =
array_ip.stream()
.collect(Collectors.groupingBy(class_ip::getIP,
Collectors.mapping(class_ip::getTitle,
Collectors.toList())));