2015-08-31 10 views
6

Ho una lista della Classe A, che include un Elenco stesso.Come espandere e fare riorganizzare un elenco di elenchi utilizzando Java 8 Stream?

public class A { 
    public double val; 
    public String id; 
    public List<String> names = new ArrayList<String>(); 
    public A(double v, String ID, String name) 
    { 
     val = v; 
     id = ID; 
     names.add(name); 
    } 

static public List<A> createAnExample() 
{ 
    List<A> items = new ArrayList<A>(); 

    items.add(new A(8.0,"x1","y11")); 
    items.add(new A(12.0, "x2", "y21")); 
    items.add(new A(24.0,"x3","y31")); 
    items.get(0).names.add("y12"); 
    items.get(1).names.add("y11"); 
    items.get(1).names.add("y31"); 
    items.get(2).names.add("y11"); 
    items.get(2).names.add("y32"); 
    items.get(2).names.add("y33"); 
    return items; 
} 

L'obiettivo è di sommare oltre il valore medio per ID sopra la Lista. Ho aggiunto il codice nella funzione Main usando un flusso Java 8. La mia domanda è come posso riscriverlo in un modo più elegante senza utilizzare la seconda matrice e il ciclo for.

static public void main(String[] args) { 
    List<A> items = createAnExample(); 

    List<A> items2 = new ArrayList<A>(); 
    for (int i = 0; i < items.size(); i++) { 
     List<String> names = items.get(i).names; 
     double v = items.get(i).val/names.size(); 
     String itemid = items.get(i).id; 
     for (String n : names) { 
      A item = new A(v, itemid, n); 
      items2.add(item); 
     } 
    } 
    Map<String, Double> x = items2.stream().collect(Collectors.groupingBy(item -> 
      item.names.isEmpty() ? "NULL" : item.names.get(0), Collectors.summingDouble(item -> item.val))); 
    for (Map.Entry entry : x.entrySet()) 
     System.out.println(entry.getKey() + " --> " + entry.getValue()); 
} 

risposta

4

È possibile farlo con flatMap:

x = items.stream() 
    .flatMap(a -> a.names.stream() 
     .map(n -> new AbstractMap.SimpleEntry<>(n, a.val/a.names.size())) 
    ).collect(groupingBy(
     Map.Entry::getKey, summingDouble(Map.Entry::getValue) 
    )); 

Se vi trovate a che fare con problemi come questi, spesso, si consideri un metodo statico per creare un Map.Entry:

static<K,V> Map.Entry<K,V> entry(K k, V v) { 
    return new AbstractMap.SimpleImmutableEntry<>(k,v); 
} 

Poi si avrebbe un aspetto meno dettagliato .map(n -> entry(n, a.val/a.names.size()))

1

In m y free library StreamEx che estende l'API Stream standard ci sono operazioni speciali che aiutano a costruire mappe così complesse. Utilizzando lo StreamEx il problema può essere risolto in questo modo:

Map<String, Double> x = StreamEx.of(createAnExample()) 
    .mapToEntry(item -> item.names, item -> item.val/item.names.size()) 
    .flatMapKeys(List::stream) 
    .grouping(Collectors.summingDouble(v -> v)); 

Qui mapToEntry crea flusso di voci della mappa (i cosiddetti EntryStream) in cui le chiavi sono liste di nomi e valori sono mediati vals. Successivamente usiamo flatMapKeys per appiattire le chiavi lasciando i valori così come sono (quindi abbiamo il flusso di Entry<String, Double>). Infine li raggruppiamo insieme sommando i valori per le chiavi ripetute.

Problemi correlati