Java 8 group by sum condition - group-by

I have an object Officer
public class Officer {
private String name;
private int totalDaysInOffice;
public Officer(String name, int totalDaysInOffice) {
this.name = name;
this.totalDaysInOffice = totalDaysInOffice;
}
#Override
public String toString() {
return "Officer{" +
"name='" + name + '\'' +
", totalDaysInOffice=" + totalDaysInOffice +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTotalDaysInOffice() {
return totalDaysInOffice;
}
public void setTotalDaysInOffice(int totalDaysInOffice) {
this.totalDaysInOffice = totalDaysInOffice;
}
}
Here each officer have spent days in office(just made up variable).
What I want to do is the divide the officers once I have the sum of days 10000 in separate list
Based on example below , I want to have list with
one list with John , Matthew , and Robert since they sum to more 10K
One list with Patrick as he has 10K
Dave would be in separate list.
I have tried group by but not sure how can I add this condition.
public class OffierExample {
public static void main(String[] args) {
List<Officer> officerList = new ArrayList<>();
officerList.add(new Officer("John",5000));
officerList.add(new Officer("Matthew",3000));
officerList.add(new Officer("Robert",2000));
officerList.add(new Officer("Dave",2000));
officerList.add(new Officer("Patrick",10000));
Map<Officer, Integer> collect = officerList.stream().collect(Collectors.groupingBy(o -> o, Collectors.summingInt(Officer::getTotalDaysInOffice)));
System.out.println(collect);
}
}
Is there anyways it can be done in Java 8
**
*****UPDATE*****
**
I have achieved using traditional loop but I want to use Java 8 group by if possible
public class OffierExample {
public static void main(String[] args) {
List<Officer> officerList = new ArrayList<>();
officerList.add(new Officer("John", 5000));
officerList.add(new Officer("Matthew", 3000));
officerList.add(new Officer("Robert", 2000));
officerList.add(new Officer("Dave", 2000));
officerList.add(new Officer("Patrick", 10000));
officerList.add(new Officer("YYYY", 600));
officerList.add(new Officer("XXXX", 600));
//keep totalDaysInOfficeSum
int totalDaysInOfficeSum = 0;
//the final list
List<List<Officer>> off = Lists.newArrayList();
//the working list
List<Officer> tempOffList = Lists.newArrayList();
for (Officer officer : officerList) {
//get sum
totalDaysInOfficeSum = totalDaysInOfficeSum + officer.getTotalDaysInOffice();
//if sum is more than 10K or equal
if (totalDaysInOfficeSum >= 10000) {
//add it in temp list
tempOffList.add(officer);
//add in master list
off.add(tempOffList);
//reset temp list
tempOffList = new ArrayList<>();
//reset sum
totalDaysInOfficeSum = 0;
continue;
}
//add in temp list
tempOffList.add(officer);
}
//any left over
if (!tempOffList.isEmpty()) {
off.add(tempOffList);
}
//printint out
System.out.println("Officers list =" + off.size());
off.forEach(o -> {
System.out.println("List size:" + o.size());
o.forEach(oo -> {
System.out.println(oo.getName() + "::" + oo.getTotalDaysInOffice());
});
System.out.println("====================");
});
}
}
Output
Officers list =3
List size:3
John::5000
Matthew::3000
Robert::2000
====================
List size:2
Dave::2000
Patrick::10000
====================
List size:2
YYYY::600
XXXX::600
====================

Something like this:
List<List<Officer>> result = officerList.stream().collect(Collector.of(
() -> new ArrayList<List<Officer>>(),
(list, entry) -> {
if (list.size() == 0) {
List<Officer> inner = new ArrayList<>();
inner.add(entry);
list.add(inner);
} else {
List<Officer> last = list.get(list.size() - 1);
int sum = last.stream().mapToInt(Officer::getTotalDaysInOffice).sum();
if (sum < 10_000) {
last.add(entry);
} else {
List<Officer> inner = new ArrayList<>();
inner.add(entry);
list.add(inner);
}
}
},
(left, right) -> {
throw new IllegalArgumentException("Not for parallel");
}));

Here is the solution with my library:
MutableInt sum = MutableInt.of(0);
List<List<Officer>> off = Stream.of(officerList)
.splitToList(officer -> sum.getAndSet(sum.value() < 10000 ? sum.value() + officer.getTotalDaysInOffice() : 0) < 10000)
.toList();
Or:
List<List<Officer>> off = Seq.of(officerList)
.split(officer -> sum.getAndSet(sum.value() < 10000 ? sum.value() + officer.getTotalDaysInOffice() : 0) < 10000);

Java 8 way
List<Officer> officerList = new ArrayList<>();
officerList.add(new Officer("John", 5000));
officerList.add(new Officer("Matthew", 3000));
officerList.add(new Officer("Robert", 2000));
officerList.add(new Officer("Dave", 2000));
officerList.add(new Officer("Patrick", 10000));
List<List<Officer>> separatedOfficerLists = officerList.stream()
.sorted(Comparator.comparing(Officer::getTotalDaysInOffice).reversed())
.collect(Collectors.groupingByConcurrent(o -> {
int totalDays = o.getTotalDaysInOffice();
int divisor = (totalDays / 10000) + 1;
return (divisor * 10000) - totalDays;
})).entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.collect(Collectors.toList());
System.out.println(separatedOfficerLists);

Related

Translating java DFS algorithm code to Dart

I've been doing some research to find a suitable algorithm for suggesting friends. I came across DFS, but I've never implemented it in Dart before. Could someone please help me t translate it into Dart? Below is the java code:
public class SuggestFriendsDFS<T> {
private HashMap<T, ArrayList<T>> adj = new HashMap<>(); //graph
private List<Set<T>> groups = new ArrayList<>();
public void addFriendship(T src, T dest) {
adj.putIfAbsent(src, new ArrayList<T>());
adj.get(src).add(dest);
adj.putIfAbsent(dest, new ArrayList<T>());
adj.get(dest).add(src);
}
//V is total number of people, E is number of connections
private void findGroups() {
Map<T, Boolean> visited = new HashMap<>();
for (T t: adj.keySet())
visited.put(t, false);
for (T t:adj.keySet()) {
if (!visited.get(t)) {
Set<T> group = new HashSet<>();
dfs(t, visited, group);
groups.add(group);
}
}
}
//DFS + memoization
private void dfs(T v, Map<T, Boolean> visited, Set<T> group ) {
visited.put(v,true);
group.add(v);
for (T x : adj.get(v)) {
if (!visited.get(x))
dfs(x, visited, group);
}
}
public Set<T> getSuggestedFriends (T a) {
if (groups.isEmpty())
findGroups();
Set<T> res = new HashSet<>();
for (Set<T> t : groups) {
if (t.contains(a)) {
res = t;
break;
}
}
if (res.size() > 0)
res.remove(a);
return res;
}
}
I'm aware it's too much to ask, but any help will be much appreciated as I tried to translate it and ended up getting loads of errors. Thanks in advance!(: For reference, this is where I found the explanation for the java code.
I tried https://sma.github.io/stuff/java2dartweb/java2dartweb.html that does automatic Java to Dart conversion but it doesn't work well as soon as the code is a bit complex.
See the full conversion below, you can try it in Dartpad
import 'dart:collection';
class SuggestFriendsDFS<T> {
final HashMap<T, List<T>> _adj = HashMap(); //graph
final List<Set<T>> groups = [];
//Time O(1), Space O(1)
void addFriendship(T src, T dest) {
_adj.putIfAbsent(src, () => <T>[]);
_adj[src]!.add(dest);
_adj.putIfAbsent(dest, () => <T>[]);
_adj[dest]!.add(src);
}
//DFS wrapper, Time O(V+E), Space O(V)
//V is total number of people, E is number of connections
void findGroups() {
Map<T, bool> visited = HashMap();
for (T t in _adj.keys) {
visited[t] = false;
}
for (T t in _adj.keys) {
if (visited[t] == false) {
Set<T> group = HashSet();
_dfs(t, visited, group);
groups.add(group);
}
}
}
//DFS + memoization, Time O(V+E), Space O(V)
void _dfs(T v, Map<T, bool> visited, Set<T> group) {
visited[v] = true;
group.add(v);
for (T x in _adj[v] ?? []) {
if ((visited[x] ?? true) == false) _dfs(x, visited, group);
}
}
//Time O(V+E), Space O(V)
Set<T> getSuggestedFriends(T a) {
if (groups.isEmpty) findGroups();
var result = groups.firstWhere((element) => element.contains(a),
orElse: () => <T>{});
if (result.isNotEmpty) result.remove(a);
return result;
}
}
void main() {
SuggestFriendsDFS<String> g = SuggestFriendsDFS();
g.addFriendship("Ashley", "Christopher");
g.addFriendship("Ashley", "Emily");
g.addFriendship("Ashley", "Joshua");
g.addFriendship("Bart", "Lisa");
g.addFriendship("Bart", "Matthew");
g.addFriendship("Christopher", "Andrew");
g.addFriendship("Emily", "Joshua");
g.addFriendship("Jacob", "Christopher");
g.addFriendship("Jessica", "Ashley");
g.addFriendship("JorEl", "Zod");
g.addFriendship("KalEl", "JorEl");
g.addFriendship("Kyle", "Lex");
g.addFriendship("Kyle", "Zod");
g.addFriendship("Lisa", "Marge");
g.addFriendship("Matthew", "Lisa");
g.addFriendship("Michael", "Christopher");
g.addFriendship("Michael", "Joshua");
g.addFriendship("Michael", "Jessica");
g.addFriendship("Samantha", "Matthew");
g.addFriendship("Samantha", "Tyler");
g.addFriendship("Sarah", "Andrew");
g.addFriendship("Sarah", "Christopher");
g.addFriendship("Sarah", "Emily");
g.addFriendship("Tyler", "Kyle");
g.addFriendship("Stuart", "Jacob");
g.findGroups();
print(g.groups);
String name = "Andrew";
print("Suggestion friends of " +
name +
": " +
g.getSuggestedFriends(name).toString());
}

TableView, TableColumns vanish off the right edge when resizing

Using some custom resizing behaviour I'm losing columns off the right side of the TableView. I have to use UNCONSTRAINED_RESIZE_POLICY (or maybe write a custom POLICY) so that I can size some of the columns to their content.
I have some custom behaviour for the resizing of columns in the TableViews I use in my application.
I use the reflection pattern to autoresize some columns to their content when the data first populates. The remaining columns width is set to a proportion of the remaining width (if there are 3 columns not being autoresized then remaining width/3=column width).
I also have a column width listener which will listen for when a user drags column widths or double clicks on the header divider to size the column to it's content. I also listen to the width of the table itself and then assign any new extra width to the last column.
The above works ok but the issue is when a user resizes a column or multiple columns to the point the last column is as small as it can go columns will start to getting pushed off the right side of the TableView. It makes sense it would do this as I have my POLICY set to UNCONSTRAINED. I obviously can't use CONSTRAINED_RESIZE_POLICY or the above logic won't work.
Is there a custom policy out there that will reduce the rightmost columns inside 1 by 1 as the user increases the column width, so the right column first until it's as small as it can be, then the next rightmost and so on. Or do I need to write this behaviour? I did come across a Koitlin based POLICY in TorpedoFX that looked interesting but I'd rather stay pure Java.
Basically the outcome I want is what I have now but any user resizing just reduces the right-most column to a minimum size, then the next right-most and so on until all the columns to the right of the column the user is resizing are at minimum size but are still visible on the TableView. If there are no columns to the right that can be resized then the user shouldn't be able to resize their column without first resizing a column to the left.
Columns should never disappear off the right side of the TableView.
I've written a test class that mimics this behaviour, it's slightly verbose in places and would be refactored in the real application.
package application;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Skin;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableColumnBase;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TableViewSample extends Application {
private TableView<TableData> table = new TableView<TableData>();
private ObservableList<TableData> data = FXCollections.observableArrayList();
private boolean columnResizeOperationPerformed = false;
private String resizeThreeColumn = "";
private String resizeFourColumn = "";
private String resizeSixColumn = "";
private final ExecutorService executorService = Executors.newFixedThreadPool(1);
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setWidth(1300);
stage.setHeight(600);
TableColumn<TableData, String> oneColumn = new TableColumn<>("One");
TableColumn<TableData, String> twoColumn = new TableColumn<>("Two");
TableColumn<TableData, String> threeColumn = new TableColumn<>("Three");
TableColumn<TableData, String> fourColumn = new TableColumn<>("Four");
TableColumn<TableData, String> fiveColumn = new TableColumn<>("Five");
TableColumn<TableData, String> sixColumn = new TableColumn<>("Six");
TableColumn<TableData, String> sevenColumn = new TableColumn<>("");
TableColumn<TableData, String> eightColumn = new TableColumn<>("");
TableColumn<TableData, String> nineColumn = new TableColumn<>("Nine");
TableColumn<TableData, String> tenColumn = new TableColumn<>("Ten");
TableColumn<TableData, String> elevenColumn = new TableColumn<>("Eleven");
TableColumn<TableData, String> twelveColumn = new TableColumn<>("Twelve");
TableColumn<TableData, String> thirteenColumn = new TableColumn<>("Thirteen");
TableColumn<TableData, String> lastColumn = new TableColumn<>("Last");
table.setEditable(false);
table.setPrefWidth(1100);
table.setMaxWidth(1100);
table.setItems(data);
table.getColumns().addAll(oneColumn, twoColumn, threeColumn, fourColumn, fiveColumn, sixColumn, sevenColumn, eightColumn, nineColumn, tenColumn, elevenColumn, twelveColumn, thirteenColumn, lastColumn);
table.setFixedCellSize(25.0);
// This cellValueFactory code could be refactored in the real application
oneColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("oneColumn"));
oneColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getOneColumn());
}
});
twoColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("twoColumn"));
twoColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getTwoColumn());
}
});
threeColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("threeColumn"));
threeColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getThreeColumn());
}
});
fourColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("fourColumn"));
fourColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getFourColumn());
}
});
fiveColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("fiveColumn"));
fiveColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getFiveColumn());
}
});
sixColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("sixColumn"));
sixColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getSixColumn());
}
});
sevenColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("sevenColumn"));
sevenColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getSevenColumn());
}
});
eightColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("eightColumn"));
eightColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getEightColumn());
}
});
nineColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("nineColumn"));
nineColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getNineColumn());
}
});
tenColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("tenColumn"));
tenColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getTenColumn());
}
});
elevenColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("elevenColumn"));
elevenColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getElevenColumn());
}
});
twelveColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("twelveColumn"));
twelveColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getTwelveColumn());
}
});
thirteenColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("thirteenColumn"));
thirteenColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getThirteenColumn());
}
});
lastColumn.setCellValueFactory(new PropertyValueFactory<TableData, String>("lastColumn"));
lastColumn.setCellValueFactory(new Callback<CellDataFeatures<TableData, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<TableData, String> p) {
return new ReadOnlyObjectWrapper(p.getValue().getLastColumn());
}
});
// using CONSTRAINED_RESIZE_POLICY will cause all kinds of odd behaviour because of the autoresize and then the columnWidthListener below.
table.setColumnResizePolicy(TableView.UNCONSTRAINED_RESIZE_POLICY);
table.getItems().addListener(new ListChangeListener<TableData>() {
#Override
public void onChanged(Change<? extends TableData> c) {
// check to see if any of the data coming in has column 3 or 4 values that columns can be resized with
if (!columnResizeOperationPerformed) {
boolean outerBreak = false;
while (c.next() && !outerBreak) {
List<? extends TableData> addedSubList = c.getAddedSubList();
if (!addedSubList.isEmpty()) {
for (TableData data : addedSubList) {
outerBreak = checkForColThreeOrFourData(data);
}
}
}
}
// resize some columns to fit contents, other columns to take up remaining space
if (!columnResizeOperationPerformed && !table.getItems().isEmpty()) {
// only prevent future column resizing if the threeColumn has some valid data to size on
if (resizeThreeColumn.length() > 0) {
columnResizeOperationPerformed = true;
}
double totalWidth = 0;
totalWidth = autosizeColumn(oneColumn);
totalWidth += autosizeColumn(threeColumn);
totalWidth += autosizeColumn(fourColumn);
totalWidth += autosizeColumn(sixColumn);
totalWidth += autosizeColumn(sevenColumn);
totalWidth += autosizeColumn(eightColumn);
totalWidth += autosizeColumn(nineColumn);
totalWidth += autosizeColumn(tenColumn);
totalWidth += autosizeColumn(elevenColumn);
totalWidth += autosizeColumn(twelveColumn);
totalWidth += autosizeColumn(lastColumn);
double remainingWidth = table.getWidth() - totalWidth;
sizeColumn(twoColumn, remainingWidth / 4.0);
sizeColumn(fiveColumn, remainingWidth / 4.0);
sizeColumn(thirteenColumn, remainingWidth / 4.0);
table.requestLayout();
}
}
});
ChangeListener<? super Number> columnWidthListener = (obs, ov, nv) -> {
double totalWidth = table.getColumns().stream()
.filter(tc -> !tc.equals(lastColumn))
.mapToDouble(TableColumnBase::getWidth)
.sum();
sizeColumn(lastColumn, table.getWidth() - totalWidth);
};
// listen for any column resizing or table width changes and assign extra width to the lastColumn above
table.getColumns().stream()
.filter(tc -> !tc.equals(lastColumn)).forEach(tc -> {
tc.widthProperty().addListener(columnWidthListener);
});
table.widthProperty().addListener(columnWidthListener);
HBox hBox = new HBox(table);
HBox.setHgrow(table, Priority.ALWAYS);
((Group) scene.getRoot()).getChildren().addAll(hBox);
stage.setScene(scene);
stage.show();
// create Task to update the table data after the UI is constructed so that the column autoresizing code above is applied as data is populated.
Task task = new Task() {
#Override
protected Object call() {
try {
Thread.sleep(100);
Platform.runLater(() -> {
updateTableData();
});
}
catch (Exception ex) {}
return null;
}
};
executorService.submit(task);
}
/**
* A test version of a check from the real application to make sure resizing of columns happens when column data of specific columns is valid
*
* #param tableData
* #return
*/
private boolean checkForColThreeOrFourData(TableData tableData) {
if (resizeThreeColumn.length() == 0) {
resizeThreeColumn = tableData.getThreeColumn();
}
if (resizeFourColumn.length() == 0) {
resizeFourColumn = tableData.getFourColumn();
}
if (resizeSixColumn.length() == 0) {
resizeSixColumn = tableData.getSixColumn();
}
if ((resizeThreeColumn.length() > 0) && resizeFourColumn.length() > 0 && resizeSixColumn.length() > 0) { return true; }
return false;
}
public void sizeColumn(TableColumn<?, ?> column, double width) {
column.setPrefWidth(width);
}
public static double autosizeColumn(TableColumn<?, ?> column) {
final TableView<?> tableView = column.getTableView();
final Skin<?> skin = tableView.getSkin();
final int rowsToMeasure = -1;
try {
Method method = skin.getClass().getDeclaredMethod("resizeColumnToFitContent", TableColumn.class, int.class);
method.setAccessible(true);
method.invoke(skin, column, rowsToMeasure);
}
catch (Exception e) {
e.printStackTrace();
}
return column.getWidth();
}
private void updateTableData() {
data.setAll(Arrays.asList(new TableData("Manufacturer1", "User 1", "value12345", "desc12345", "defaultName", "17:04:49 15/05/19", "200", "0", "0", "3", "12", "2", "16-15-14", "80"),
new TableData("Manufacturer2", "User 2", "value67890", "desc67890", "", "17:06:38 15/05/19", "100", "0", "0", "3", "11", "2", "16-15-14", "82")));
}
class TableData implements Serializable {
private static final long serialVersionUID = 1L;
private String oneColumn;
private String twoColumn;
private String threeColumn;
private String fourColumn;
private String fiveColumn;
private String sixColumn;
private String sevenColumn;
private String eightColumn;
private String nineColumn;
private String tenColumn;
private String elevenColumn;
private String twelveColumn;
private String thirteenColumn;
private String lastColumn;
public TableData(String oneColumn, String twoColumn, String threeColumn, String fourColumn, String fiveColumn, String sixColumn, String sevenColumn, String eightColumn, String nineColumn, String tenColumn, String elevenColumn,
String twelveColumn, String thirteenColumn, String lastColumn) {
this.oneColumn = oneColumn;
this.twoColumn = twoColumn;
this.threeColumn = threeColumn;
this.fourColumn = fourColumn;
this.fiveColumn = fiveColumn;
this.sixColumn = sixColumn;
this.sevenColumn = sevenColumn;
this.eightColumn = eightColumn;
this.nineColumn = nineColumn;
this.tenColumn = tenColumn;
this.elevenColumn = elevenColumn;
this.twelveColumn = twelveColumn;
this.thirteenColumn = thirteenColumn;
this.lastColumn = lastColumn;
}
public String getOneColumn() {
return oneColumn;
}
public String getTwoColumn() {
return twoColumn;
}
public String getThreeColumn() {
return threeColumn;
}
public String getFourColumn() {
return fourColumn;
}
public String getFiveColumn() {
return fiveColumn;
}
public String getSixColumn() {
return sixColumn;
}
public String getSevenColumn() {
return sevenColumn;
}
public String getEightColumn() {
return eightColumn;
}
public String getNineColumn() {
return nineColumn;
}
public String getTenColumn() {
return tenColumn;
}
public String getElevenColumn() {
return elevenColumn;
}
public String getTwelveColumn() {
return twelveColumn;
}
public String getThirteenColumn() {
return thirteenColumn;
}
public String getLastColumn() {
return lastColumn;
}
}
}
As mentioned above this code will auto resize the selected columns and assign the remaining width equally to the other columns.
It will listen to user column width adjustments correctly.
What it won't do is prevent the columns to the right edge vanishing off the view. I would like the right columns to be reduced in width to accomodate the user column width increase in the order described above, right-most first continuing in from the right as columns reach their minimum.
Thanks for any help.

How to get the average of a generic array list in java?

i'm having trouble getting the average of a generic array list of type T.
You should use <T extends Number> generic signature to specify the type of the Number types, plus, you should use instanceof keyword. A simple dummy demo here;
Test Code
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();
List<Float> floatList = new ArrayList<Float>();
for(int i = 0; i < 10; i++)
{
integerList.add(new Integer(i+1));
doubleList.add(new Double(i+1));
floatList.add(new Float(i+1));
}
Utility<Integer> utilityInteger = new Utility<Integer>(integerList);
Utility<Double> utilityDouble = new Utility<Double>(doubleList);
Utility<Float> utilityFloat = new Utility<Float>(floatList);
System.out.println("Integer average: " + utilityInteger.getAverage());
System.out.println("Double average : " + utilityDouble.getAverage());
System.out.println("Float average : " + utilityFloat.getAverage());
}
public static class Utility<T extends Number>
{
// Fields
private List<T> list;
private Object average;
// Constructor
#SuppressWarnings("unchecked")
public Utility(List<T> list)
{
this.list = list;
T sample = list.get(0);
if(sample instanceof Double)
{
doAverageDouble((List<Double>) list);
}
else if (sample instanceof Integer)
{
doAverageInteger((List<Integer>) list);
}
else if (sample instanceof Float)
{
doAverageFloat((List<Float>) list);
}
else
{
throw new IllegalStateException("Constructor must be initialiez with either of Double, Integer or Float list");
}
}
// Methods
private void doAverageDouble(List<Double> list) {
Double sum = new Double(0);
for(Double d : list)
{
sum += d;
}
average = sum/new Double(list.size());
}
private void doAverageInteger(List<Integer> list) {
Integer sum = new Integer(0);
for(Integer d : list)
{
sum += d;
}
average = sum/new Integer(list.size());
}
private void doAverageFloat(List<Float> list) {
Float sum = new Float(0);
for(Float d : list)
{
sum += d;
}
average = sum/new Float(list.size());
}
Object getAverage()
{
return average;
}
}
}
Console Output
Integer average: 5
Double average : 5.5
Float average : 5.5

Gwt CheckBoxCell check uncheck issue

I am not able to check or uncheck a Gwt CheckBoxCell . It works fine in Chrome but it doesn't work at all in mozilla . What wrong i am doing ? Please Suggest . When i am selecting selectAllHeader not able to check/uncheck in mozilla though same works in chrome.
DataGridTableRowModel headerRow = dataGridTableRowList.get(0);
E12CommonUtils.printOnConsole("IN createTableComponent================="+ headerRow);
int width = 50;
final MultiSelectionModel<DataGridTableRowModel> multiSelectionModel = new MultiSelectionModel<DataGridTableRowModel>();
this.setSelectionModel(multiSelectionModel,DefaultSelectionEventManager.<DataGridTableRowModel> createCheckboxManager(0));
multiSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
{
public void onSelectionChange(SelectionChangeEvent event)
{
count++;
E12CommonUtils.printOnConsole("Inside select : ");
Set<DataGridTableRowModel> set = multiSelectionModel.getSelectedSet();
Iterator it = set.iterator();
selectedValues = new StringBuffer();
selectedNames = new StringBuffer();
while (it.hasNext())
{
DataGridTableRowModel row = (DataGridTableRowModel) it.next();
E12CommonUtils.printOnConsole("Inside select = "+ row.getCellText(1));
selectedValues.append(row.getCellText(1) + ":");
E12CommonUtils.printOnConsole("AFTER APPENDING selectedValues = "+ row.getCellText(1));
selectedNames.append(row.getCellData(1).getName() + ":");
}
}
});
E12CommonUtils.printOnConsole("IN $$$$$$$$$$$$$$$$$=================135");
final Column<DataGridTableRowModel, Boolean> checkColumn = new Column<DataGridTableRowModel, Boolean>(new E12CheckBoxCell(false, false))
{
#Override
public Boolean getValue(DataGridTableRowModel dataGridTRModel)
{
boolean isSelected = multiSelectionModel.isSelected(dataGridTRModel);
E12CommonUtils.printOnConsole("checkColumn isSelected["+ isSelected + "]\tprotect["+ dataGridTRModel.getCellData(0).isProtect() + "]");
getFieldUpdater().update(0, dataGridTRModel, isSelected); // If commented deselect all works
return isSelected;
}
};
checkColumn.setFieldUpdater(new FieldUpdater<DataGridTableRowModel, Boolean>()
{
#Override
public void update(int idx,DataGridTableRowModel dataGridTRModel,Boolean value)
{
try
{
CellData cellData = dataGridTRModel.getCellData(0);
cellData.setData(String.valueOf(value));
dataGridTRModel.setCellData(0, cellData);
multiSelectionModel.setSelected(dataGridTRModel, value);
}
catch (Exception e)
{
Window.alert("Exception in checkColumn.setFieldUpdater : "+ e.getMessage());
}
}
});
CheckboxCell checkAll = new CheckboxCell();
// E12CheckBoxCell checkAll = new E12CheckBoxCell(false, false);
Header<Boolean> selectAllHeader = new Header<Boolean>(checkAll){
#Override
public Boolean getValue()
{
E12CommonUtils.printOnConsole("IN getValue()=========");
return false;
}
};
selectAllHeader.setUpdater(new ValueUpdater<Boolean>(){
#Override
public void update(Boolean selected)
{
for (DataGridTableRowModel ele : getVisibleItems())
{
E12CommonUtils.printOnConsole("IN update**************");
multiSelectionModel.setSelected(ele, selected);
}
}
});
this.addColumn(checkColumn, selectAllHeader);
this.setColumnWidth(checkColumn, 20, Unit.PX);
for (int i = 1; i < headerRow.getRowData().size(); i++)
{
final int index = i;
final String colName = headerRow.getCellData(index).getName();
width = 25;// TODO
E12CustomColumn column = new E12CustomColumn(index, false);
this.setColumnWidth(column, width + "px");
// Add a selection model to handle user selection.
ResizableHeader<DataGridTableRowModel> header = new ResizableHeader<DataGridTableRowModel>(colName, this, column) {
#Override
public String getValue()
{
return colName;
}
};
// this.addColumn(column, selectAllHeader,header);
// this.addColumn(selectAllHeader, header);
this.addColumn(column, header);
}
dataProvider.addDataDisplay(this);
dataProvider.refresh();
it may be browser compatibility issue - meta tag might help you
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
For more details follow below url -
What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Reactive Extensions Group By, Unique BufferWindow till time span with cancellation

I have a Hot stream of events coming of following type:
Event
{
string name;
int state ; // its 1 or 2 ie active or unactive
}
there is a function which provides parent name of given name - string GetParent(string name)
I need to buffer event per parent for 2 minutes, if during this 2 minute , i recv any event for child with state =2 for a given parent , this buffer should cancel and should output 0 otherwise i get the count of the events recvd .
I know I have to use GroupBy to partition, and then buffer and then count but i am unable to think of a way by which i create Buffer which is unique per parent, i though of using Distinct but this doesnt solve the problem, for i only dont want to create buffer till the parent is active (as once the parent's buffer gets cancelled or 2 minutes is over, the parent buffer can be created again)
So I understand I need to create a custom buffer which checks the condition for creating buffer, but how do i do this via reactive extensions.
Any help will be greatly appreciated.
regards
Thanks Brandon for your help. This is the main program I am using for testing. Its not working.As I am new to reactive extension problem can be in the way i am testing
namespace TestReactive
{
class Program
{
static int abc = 1;
static void Main(string[] args)
{
Subject<AEvent> memberAdded = new Subject<AEvent>();
//ISubject<AEvent, AEvent> syncedSubject = new ISubject<AEvent, AEvent>();
var timer = new Timer { Interval = 5 };
timer.Enabled = true;
timer.Elapsed += (sender, e) => MyElapsedMethod(sender, e, memberAdded);
var bc = memberAdded.Subscribe();
var cdc = memberAdded.GroupBy(e => e.parent)
.SelectMany(parentGroup =>
{
var children = parentGroup.Publish().RefCount();
var inactiveChild = children.SkipWhile(c => c.state != 2).Take(1).Select(c => 0);
var timer1 = Observable.Timer(TimeSpan.FromSeconds(1));
var activeCount = children.TakeUntil(timer1).Count();
return Observable.Amb(activeCount, inactiveChild)
.Select(count => new { ParentName = parentGroup.Key, Count = count });
});
Observable.ForEachAsync(cdc, x => WriteMe("Dum Dum " + x.ParentName+x.Count));
// group.Dump("Dum");
Console.ReadKey();
}
static void WriteMe(string sb)
{
Console.WriteLine(sb);
}
static void MyElapsedMethod(object sender, ElapsedEventArgs e, Subject<AEvent> s)
{
AEvent ab = HelperMethods.GetAlarm();
Console.WriteLine(abc + " p =" + ab.parent + ", c = " + ab.name + " ,s = " + ab.state);
s.OnNext(ab);
}
}
}
public static AEvent GetAlarm()
{
if (gp> 4)
gp = 1;
if (p > 4)
p = 1;
if (c > 4)
c = 1;
AEvent a = new AEvent();
a.parent = "P" + gp + p;
a.name = "C" + gp + p + c;
if (containedKeys.ContainsKey(a.name))
{
a.state = containedKeys[a.name];
if (a.state == 1)
containedKeys[a.name] = 2;
else
containedKeys[a.name] = 1;
}
else
{
containedKeys.TryAdd(a.name, 1);
}
gp++; p++; c++;
return a;
}
So this method , generates a event for Parent at each tick. It generates event for parent P11,P22,P33,P44 with State =1 and then followed by events for Parent P11,P22,P33,P44 with State =2
I am using Observable.ForEach to print the result, I see its being called 4 times and after that its nothing, its like cancellation of group is not happening
Assuming that a two minute buffer for each group should open as soon as the first event for that group is seen, and close after two minutes or a zero state is seen, then I think the following works:
public static IObservable<EventCount> EventCountByParent(
this IObservable<Event> source, IScheduler scheduler)
{
return Observable.Create<EventCount>(observer => source.GroupByUntil(
evt => GetParent(evt.Name),
evt => evt,
group =>
#group.Where(evt => evt.State == 2)
.Merge(Observable.Timer(
TimeSpan.FromMinutes(2), scheduler).Select(_ => Event.Null)))
.SelectMany(
go =>
go.Aggregate(0, (acc, evt) => (evt.State == 2 ? 0 : acc + 1))
.Select(count => new EventCount(go.Key, count))).Subscribe(observer));
}
With EventCount (implementing equality overrides for testing) as:
public class EventCount
{
private readonly string _name;
private readonly int _count;
public EventCount(string name, int count)
{
_name = name;
_count = count;
}
public string Name { get { return _name; } }
public int Count { get { return _count; } }
public override string ToString()
{
return string.Format("Name: {0}, Count: {1}", _name, _count);
}
protected bool Equals(EventCount other)
{
return string.Equals(_name, other._name) && _count == other._count;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((EventCount) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((_name != null ? _name.GetHashCode() : 0)*397) ^ _count;
}
}
}
And Event as:
public class Event
{
public static Event Null = new Event(string.Empty, 0);
private readonly string _name;
private readonly int _state;
public Event(string name, int state)
{
_name = name;
_state = state;
}
public string Name { get { return _name; } }
public int State { get { return _state; } }
}
I did a quick (i.e. not exhaustive) test with Rx-Testing:
public class EventCountByParentTests : ReactiveTest
{
private readonly TestScheduler _testScheduler;
public EventCountByParentTests()
{
_testScheduler = new TestScheduler();
}
[Fact]
public void IsCorrect()
{
var source = _testScheduler.CreateHotObservable(
OnNext(TimeSpan.FromSeconds(10).Ticks, new Event("A", 1)),
OnNext(TimeSpan.FromSeconds(20).Ticks, new Event("B", 1)),
OnNext(TimeSpan.FromSeconds(30).Ticks, new Event("A", 1)),
OnNext(TimeSpan.FromSeconds(40).Ticks, new Event("B", 1)),
OnNext(TimeSpan.FromSeconds(50).Ticks, new Event("A", 1)),
OnNext(TimeSpan.FromSeconds(60).Ticks, new Event("B", 2)),
OnNext(TimeSpan.FromSeconds(70).Ticks, new Event("A", 1)),
OnNext(TimeSpan.FromSeconds(140).Ticks, new Event("A", 1)),
OnNext(TimeSpan.FromSeconds(150).Ticks, new Event("A", 1)));
var results = _testScheduler.CreateObserver<EventCount>();
var sut = source.EventCountByParent(_testScheduler).Subscribe(results);
_testScheduler.Start();
results.Messages.AssertEqual(
OnNext(TimeSpan.FromSeconds(60).Ticks, new EventCount("B", 0)),
OnNext(TimeSpan.FromSeconds(130).Ticks, new EventCount("A", 4)),
OnNext(TimeSpan.FromSeconds(260).Ticks, new EventCount("A", 2)));
}
}
something like....
source.GroupBy(e => GetParent(e.name))
.SelectMany(parentGroup =>
{
var children = parentGroup.Publish().RefCount();
var inactiveChild = children.SkipWhile(c => c.state != 2).Take(1).Select(c => 0);
var timer = Observable.Timer(TimeSpan.FromMinutes(2));
var activeCount = children.TakeUntil(timer).Count();
return Observable.Amb(activeCount, inactiveChild)
.Select(count => new { ParentName = parentGroup.Key, Count = count };
});
This will give you a sequence of { ParentName, Count } objects.