以下学生姓名年龄表,剔除年龄为空的和小于18岁的,将剩下的学生分组输出 需要具体代码
张三 36
李四 null
王五 “”
马六 15
李七 25
汪八 25
开两个数组;
一个数组循环遍历,若不为空并且大于十八则输出相应下标的姓名
用个List就行
计数类问题可以考虑使用Map来帮助分组。
获取数据方式不知道要怎么拿, 读文件,sql,List?
1) SQL方式直接条件增加年龄判断即可特除, 余下部分用代码分组。
SELECT * FROM TABLE WHERE AGE >= 18 ORDER BY AGE;
2) 集合方式就老老实实将数据添加,顺带放一个内部的实体
List<Person> dataList = new ArrayList<Person>();
dataList.add(new Person("张三", "36"));
dataList.add(new Person("张1", "36"));
dataList.add(new Person("李四", null));
dataList.add(new Person("王五", ""));
dataList.add(new Person("马六", "15"));
dataList.add(new Person("马2", "15"));
// ....
循环多条数据,根据取出的年龄判断,利用HashMap的特性(键值对,且仅有一个key)。按年龄获取值,空判断后将人名拼接。
Map<String, String> map = new HashMap<String, String>();
for(Person p : dataList){
if(p.getAge() != null && !"".equals(p.getAge())){
map.put(p.getAge(), (map.get(p.getAge())== null?"":map.get(p.getAge())) + "," + p.getName());
}
}
System.out.println(map);
// {36=,张三,张1, 15=,马六,马2}
可用 JAVA 8 stream筛选、分组统计
Student类
public class Student {
private String name;
private Integer age;
public Student(){}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
return "Student: " + name + " " + age;
}
}
Demo类
import java.util.*;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student("张三", 36));
list.add(new Student("李四", null));
list.add(new Student("马六", 15));
list.add(new Student("李七", 25));
list.add(new Student("汪八", 25));
list.add(new Student("赵九", 21));
Map<Integer, List<Student>> collect = list.stream()
.filter(a -> a.getAge() != null) //剔除年龄为空
.filter(a -> a.getAge() > 18) //剔除年龄小于18岁的
.collect(Collectors.groupingBy(Student::getAge));
// collect.keySet().forEach(System.out::println);
List<Student> list2 = new ArrayList<>();
collect.keySet().forEach(x-> {
Student student = new Student();
student.setAge(x);
student.setName(collect.get(x).toString());
list2.add(student);
});
System.out.println("剩下的学生分组输出:");
list2.forEach(System.out::println);
}
}
运行结果:
用jdk8的流属性实现,即list.stream().filter(条件).collect(Collectors.groupingBy(User::getAge));