SHOW:
|
|
- or go back to the newest paste.
| 1 | package com.example.foo; | |
| 2 | ||
| 3 | import java.time.Month; | |
| 4 | import java.util.ArrayList; | |
| 5 | import java.util.Comparator; | |
| 6 | import java.util.List; | |
| 7 | import java.util.Random; | |
| 8 | import java.util.stream.Collectors; | |
| 9 | ||
| 10 | import com.example.foo.SomeClass.Foo.Type; | |
| 11 | ||
| 12 | public class SomeClass {
| |
| 13 | public static void main(final String[] args) {
| |
| 14 | - | foos.add(new Foo(Month.of(rng.nextInt(12) + 1).name(), rng.nextInt(3) + 1)); |
| 14 | + | |
| 15 | final Random rng = new Random(); | |
| 16 | - | final List<Foo> elements = foos.blub(); |
| 16 | + | final Type[] types = Foo.Type.values(); |
| 17 | // This just adds random elements: | |
| 18 | for (int i = 0; i < 100; i++) | |
| 19 | foos.add(new Foo(Month.of(rng.nextInt(12) + 1).name(), types[rng.nextInt(types.length)])); | |
| 20 | ||
| 21 | final List<Foo> elements = foos.sortedByType(); | |
| 22 | for (final Foo foo : elements) | |
| 23 | System.out.println(foo.getName()); | |
| 24 | } | |
| 25 | ||
| 26 | public static class FooContainer {
| |
| 27 | private final List<Foo> list = new ArrayList<>(); | |
| 28 | - | public List<Foo> blub() {
|
| 28 | + | |
| 29 | - | final List<Foo> result = new ArrayList<>(); |
| 29 | + | |
| 30 | - | for (int i = Foo.TYPE_A; i <= Foo.TYPE_C; i++) |
| 30 | + | |
| 31 | - | for (final Foo f : this.list) |
| 31 | + | |
| 32 | - | if (i == f.getType()) |
| 32 | + | |
| 33 | - | result.add(f); |
| 33 | + | public List<Foo> sortedByType() {
|
| 34 | - | return result; |
| 34 | + | return this.list.stream().sorted(Comparator.comparing(Foo::getType)) |
| 35 | .collect(Collectors.toList()); | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | - | public static final int TYPE_A = 1; |
| 39 | + | |
| 40 | - | public static final int TYPE_B = 2; |
| 40 | + | public static enum Type {
|
| 41 | - | public static final int TYPE_C = 3; |
| 41 | + | A, B, C; |
| 42 | } | |
| 43 | - | private int type; |
| 43 | + | |
| 44 | private Type type; | |
| 45 | private String name; | |
| 46 | - | public Foo(final String name, final int type) {
|
| 46 | + | |
| 47 | public Foo(final String name, final Type type) {
| |
| 48 | this.name = name; | |
| 49 | this.type = type; | |
| 50 | } | |
| 51 | ||
| 52 | public String getName() {
| |
| 53 | return this.name; | |
| 54 | } | |
| 55 | ||
| 56 | public void setName(final String name) {
| |
| 57 | this.name = name; | |
| 58 | } | |
| 59 | - | public int getType() {
|
| 59 | + | |
| 60 | public Type getType() {
| |
| 61 | return this.type; | |
| 62 | } | |
| 63 | - | public void setType(final int type) {
|
| 63 | + | |
| 64 | public void setType(final Type type) {
| |
| 65 | this.type = type; | |
| 66 | } | |
| 67 | } | |
| 68 | } |