java编程,具体问题如下:
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java编程,具体问题如下:相关的知识,希望对你有一定的参考价值。
集合处理排序问题,可以用java8的stream来搞定
参考代码如下:
public static void main(String[] args)Random random = new Random();
IntStream.rangeClosed(1,10).mapToObj(item -> new Student(String.valueOf(item), "Tom" + item, random.nextInt(101)))
.sorted(Comparator.comparing(Student::getScore))
.forEach(item -> System.out.println(item.toString()));
public class Student
private String id;
private String name;
private int score;
public Student(String id, String name, int score)
this.id = id;
this.name = name;
this.score = score;
@Override
public String toString()
return "name: "+ this.name + " " + "score: "+ this.score;
public String getId()
return id;
public void setId(String id)
this.id = id;
public String getName()
return name;
public void setName(String name)
this.name = name;
public int getScore()
return score;
public void setScore(int score)
this.score = score;
上面代码是按照score升序排序的,运行结果如下:
解释一下代码
IntStream.rangeClosed(1,10):这里生成了1到10个数字的stream
mapToObj:把stream中的数字转化为student对象
sorted:排序,按照student的score进行排序(默认升序)
forEach:循环所有的student,按照toString的方式打印
若想按照降序排列也很简单,在排序处再加一个reversed()方法即可
java8的stream对于集合的相关处理,排序,循环,都很好用,可以去看看
参考技术A import java.util.Date;import java.util.Random;
class StudentInfo
private String id;
private String name;
private int score;
public void setId(String id)
this.id = id;
public String getId()
return this.id;
public void setName(String name)
this.name = name;
public String getName()
return this.name;
public void setScore(int score)
this.score = score;
public int getScore()
return this.score;
public void printStudentInfo()
System.out.println("**********************");
System.out.println("id:" + this.getId());
System.out.println("name:" + this.getName());
System.out.println("score:" + this.getScore());
public class Student
static final int STUDENT_NUM = 10;
static final String ID_START = "10";
static final int SCORE_MAX = 101;
static StudentInfo stu[] = new StudentInfo[10];
static Date date = new Date();
static long seed = date.getTime();
static Random rdm = new Random(seed);
static void studentInit()
for (int i = 0; i < STUDENT_NUM; i++)
stu[i] = new StudentInfo();
stu[i].setId(ID_START + Integer.toString(i));
stu[i].setName("tom" + Integer.toString(i+1));
stu[i].setScore(rdm.nextInt(SCORE_MAX));
static void printStudentsInfo()
for (int i = 0; i < STUDENT_NUM; i++)
stu[i].printStudentInfo();
static void sort()
StudentInfo s;
for (int i = 0; i < STUDENT_NUM; i++)
for (int j = 0; j < STUDENT_NUM-i-1; j++)
if (stu[j].getScore() > stu[j+1].getScore())
s = stu[j];
stu[j] = stu[j+1];
stu[j+1] = s;
public static void main(String args[])
studentInit();
System.out.println("Before sort:");
printStudentsInfo();
sort();
System.out.println("----------------------");
System.out.println("After sort:");
printStudentsInfo();
学java没多少天,只能写成这样了
可以看一下运行结果吗?
以上是关于java编程,具体问题如下:的主要内容,如果未能解决你的问题,请参考以下文章