DulcetAirman

sort by type

Oct 10th, 2015
352
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.     final FooContainer foos = new FooContainer();
  15.     final Random rng = new Random();
  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.  
  29.     public void add(final Foo foo) {
  30.       this.list.add(foo);
  31.     }
  32.  
  33.     public List<Foo> sortedByType() {
  34.       return this.list.stream().sorted(Comparator.comparing(Foo::getType))
  35.           .collect(Collectors.toList());
  36.     }
  37.   }
  38.  
  39.   public static class Foo {
  40.     public static enum Type {
  41.       A, B, C;
  42.     }
  43.  
  44.     private Type type;
  45.     private String name;
  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.  
  60.     public Type getType() {
  61.       return this.type;
  62.     }
  63.  
  64.     public void setType(final Type type) {
  65.       this.type = type;
  66.     }
  67.   }
  68. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment