Remove nulls from an array in java - java

I have a method what should delete values from an array...
public Application[] deleteApp(String id) {
int count = 0;
for (int i = 0; i < this.apps.length; i++) {
if (this.apps[i] != null && this.apps[i].getId().equals(id)) {
this.apps[i] = null;
if (this.apps[i] == null)
count++;
}
}
Application[] withoutNulls = new Application[this.apps.length - count];
int index = 0;
for (Application app : this.apps) {
if (app != null) {
withoutNulls[index] = app;
index++;
}
}
return withoutNulls;
}
But final result is smth like:
Application[] app = {app1, app2, null};
What's wrong? I'm counting nulls, creating new array[sizeOfArray - countOfNulls], and recording only not-null values :(
upd
I have a test of that.
#Test
public void deleteAppTest() {
Tracker tracker = new Tracker();
Application testing_1 = new Application();
Application testing_2 = new Application();
Application[] test = {testing_1};
tracker.addApp(testing_1);
tracker.addApp(testing_2);
tracker.deleteApp(testing_2.getId());
assertThat(tracker.showApps(), is(test));
But method does not pass the test.
Expected: is []
but: was [, null]

Try with Lambdas
public Application[] deleteApp(String id) {
List<Application> result = Arrays.asList(apps).stream().
filter(app -> app != null &&!id.equals(app.getId())).collect(Collectors.toList());
return result.toArray(new Application[result.size()]);
}
Here it is as #Erwin Bolwidt suggested
public Application[] deleteApp(String id) {
int count = 0;
for (int i = 0; i < this.apps.length; i++) {
if (this.apps[i] != null && this.apps[i].getId().equals(id)) {
this.apps[i] = null;
count++;
}
// Move this if out into an else if
else if (this.apps[i] == null){
count++;
}
}
Application[] withoutNulls = new Application[this.apps.length - count];
int index = 0;
for (Application app : this.apps) {
if (app != null) {
withoutNulls[index] = app;
index++;
}
}
return withoutNulls;
}

Related

Pass parameter value from my implementation service to my RestController java springboot

I'm having a trouble passing the value of error i get when im returning the results of a table.
I have a method in my ServiceImpl class which return results for the table and also counts the amount of errors.
public List<Flow> getAllProcessContextWithCriteriaAndFlowCode(
String startDate, String endDate, String flowCode) {
List<FlowDto> flowDtos = new ArrayList<>(500);
flowDtos = processContextRepository
.fetch(startDate,
endDate, flowCode);
List<Flow> flows = new ArrayList();
// bodyguard
if (flowDtos == null || flowDtos.size() == 0) {
return flows;
}
int counter = 0;
StringBuilder idFonctionnelBuilder = new StringBuilder();
FlowDto currentFlowDto = null;
FlowState flowState = new FlowState();
FlowDto nextFlowDto = null;
Flow flowTemp = null;
Map<String, String> mapFlowIdsAndIdF = new HashMap<>();
int iNbreError = 0;
String sTempError = "";
for (int i = 0; i < flowDtos.size(); i++) {
currentFlowDto = flowDtos.get(i);
if ((i + 1) < flowDtos.size()) {
nextFlowDto = flowDtos.get(i + 1);
if (((nextFlowDto.getFlowId()
.equals(currentFlowDto.getFlowId())))) {
idFonctionnelBuilder.append(currentFlowDto.getIdf() + ", ");
continue;
} else {
flowTemp = new Flow();
flowTemp.setFlowId(currentFlowDto.getFlowId());
flowTemp.setLogRole(currentFlowDto.getLogRole());
Date date = null;
try {
date = inputFormat.parse(currentFlowDto
.getContextTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
flowTemp.setContextTime(outputFormat.format(date));
if (currentFlowDto.getLogRole() != null) {
iNbreError++;
flowTemp.setNbreError(iNbreError);
} else {
flowTemp.setNbreError(iNbreError);
}
flowTemp.setNbreError(iNbreError);
flows.add(flowTemp);
}
} else {
flowTemp = new Flow();
if (currentFlowDto.getLogRole() != null) {
iNbreError++;
flowTemp.setNbreError(iNbreError);
} else {
flowTemp.setNbreError(iNbreError);
}
flowTemp.setContextTime(outputFormat.format(date));
flows.add(flowTemp);
}
}
LOGGER.info("[ getAllProcessContextWithCriteriaAndFlowCode ] iNbreError : "
+ iNbreError);
getNbreError(iNbreError);
return flows;
}
Then i have another method in the same class ServiceImpl who get the number of errors and set it in a variable, the result print is always the right one here.
public int getNbreError( int iNbreError){
System.out.println("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH");
System.out.println(iNbreError);
setCountError(iNbreError);
System.out.println("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH");
System.out.println(countError);
return countError;
}
What i want to do is send this value(counterror) to my RestController which is in another class called RestController so i can send it to my angular front
#GetMapping(value = "/nbreError")
public int getCountError() {
FMServiceImpl flows = new FMServiceImpl();
int countError = 0;
int iNbreError = 0;
return fmService.getNbreError( iNbreError);
}
}
Actually the result is always 0.
Thanks for your any help or advice :)
Don't use getMethod to modify data, check principle Command–query separation (CQS)
Don't create FMServiceImpl manually, Inject FMServiceImpl as dependence to your controller. in spring, Service keeps the state by default.

how to sort ArrayList by id and add to ArrayList ArrayList<ArrayList<DataPost>>

I have mList2 with values. There are values with the same id. How can I get a List or ArrayList in which objects with the same id are grouped and add it to ArrayList>?
List<ProfileActivity.DataPost> mList2 = list;
List<List<ProfileActivity.DataPost>> output = new ArrayList<List<ProfileActivity.DataPost>>();
List<ProfileActivity.DataPost> itemsAlreadyGrouped = new ArrayList<ProfileActivity.DataPost>();
for (int i = 0; i < mList2.size(); i++) {
List<ProfileActivity.DataPost> groupList = new ArrayList<ProfileActivity.DataPost>();
boolean groupCandidateFound = false;
if (!itemsAlreadyGrouped.contains(mList2.get(i))) {
for (int j = 0; j < mList2.size(); j++) {
if (mList2.get(i).getIds_post().equals(mList2.get(j).getIds_post())) {
groupList.add(mList2.get(i));
groupCandidateFound = true;
}
}
if (groupCandidateFound) {
itemsAlreadyGrouped.add(mList2.get(i));
}
}
if (groupList.size() > 0) {
output.add(groupList);
}
}
//Let's test the logic
for (List<ProfileActivity.DataPost> group : output) {
System.out.println(group);
Toast.makeText(context, group.toString(),Toast.LENGTH_SHORT ).show();
}
DataPost
data class DataPost(var text:String? = null, var photo:String? = null,
var type:String = "",
var ids_post:String = "", var position:String? = null)
Make your ProfileActivity.DataPost class implements Comparable<ProfileActivity.DataPost> interface, the implement the compareTo(ProfileActivity.DataPost o) method
#Override
public void compareTo(ProfileActivity.DataPost o){
return getIds_post().compareTo(o.getIds_post());
}
Then just invoke Collections.sort(list)

Android - An algorithm to check recursively if a map is solvable

I am making an android Hashikawekero puzzle game, I have implemented a algorithm to spawn nodes (Islands) at random positions using a 2-d array this works fine it creates the node at random position but most of the times the map cant be solved. The map nodes spawn at random.
BoardCreation.java Class - this generates the map.
package Island_and_Bridges.Hashi;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import java.util.Random;
import static junit.framework.Assert.*;
//This class Creates the map by random using a 2d array
public class BoardCreation {
// This class member is used for random initialization purposes.
static private final Random random = new Random();
// The difficulty levels.
private static final int EASY = 0;
static public final int MEDIUM = 1;
static public final int HARD = 2;
static public final int EMPTY = 0;
private static int ConnectionFingerprint(BoardElement start, BoardElement end) {
int x = start.row * 100 + start.col;
int y = end.row * 100 + end.col;
// Swap to get always the same fingerprint independent whether we are called
// start-end or end-start
if (x > y ) {
int temp = x;
x = y;
y = temp;
}
Log.d("", String.format("%d %d" , x ,y));
return x ^ y;
}
public class State {
// The elements of the board are stored in this array.
// A value defined by "EMPTY" means that its not set yet.
public BoardElement [][] board_elements = null;
public int [][] cell_occupied = null;
// The width of the board. We only assume squared boards.
public int board_width=0;
public State(int width) {
board_width = width;
board_elements = new BoardElement[width][width];
cell_occupied = new int[width][width];
}
public State CloneWithoutConnections() {
State newstate = new State(board_width);
if (board_elements != null) {
newstate.board_elements = new BoardElement[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
for (int j = 0; j < board_elements.length; ++j) {
if (board_elements[i][j] == null)
continue;
newstate.board_elements[i][j] = board_elements[i][j].clone();
}
}
}
if (cell_occupied != null) {
assert board_elements != null;
newstate.cell_occupied = new int[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
System.arraycopy(cell_occupied[i], 0, newstate.cell_occupied[i], 0, board_elements.length);
}
}
return newstate;
}
public void AddToBridgeCache(BoardElement first, BoardElement second) {
if (first == null || second == null) { return; }
final int fingerprint = ConnectionFingerprint(first, second);
Log.d(getClass().getName(),
String.format("Fingerprint of this bridge %d", fingerprint));
// mark the end points as occupied.
cell_occupied[first.row][first.col] = fingerprint;
cell_occupied[second.row][second.col] = fingerprint;
int dcol = second.col - first.col;
int drow = second.row - first.row;
if (first.row == second.row) {
for (int i = (int) (first.col + Math.signum(dcol)); i != second.col; i += Math.signum(dcol)) {
cell_occupied[first.row][i] = fingerprint;
String.format("deleting bridge");
}
} else {
assert first.col == second.col;
for (int i = (int) (first.row + Math.signum(drow)); i != second.row; i+= Math.signum(drow)) {
cell_occupied[i][first.col] = fingerprint;
}
}
}
} // end of state
private State current_state, old_state;
static private final int WIDTH_EASY = 7;
private void NewGame(int hardness) {
switch(hardness) {
case EASY:
Log.d(getClass().getName(), "Initializing new easy game");
InitializeEasy();
old_state = getCurrentState().CloneWithoutConnections();
break;
}
}
public void ResetGame() {
if (old_state != null) {
Log.d(getClass().getName(), "Setting board_elements to old_elements");
setCurrentState(old_state.CloneWithoutConnections());
} else {
Log.d(getClass().getName(), "old_lements are zero");
}
}
public BoardCreation(int hardness) {
NewGame(hardness);
}
public boolean TryAddNewBridge(BoardElement start, BoardElement end, int count) {
assertEquals(count, 1);
assert (start != null);
assert (end != null);
final int fingerprint = ConnectionFingerprint(start, end);
Log.d(getClass().getName(),
String.format("considering (%d,%d) and (%d,%d)", start.row,start.col, end.row,end.col));
if (start.row == end.row && start.col == end.col) {
Log.d(getClass().getName(), "Same nodes selected!");
return false;
}
assert count > 0;
int dcol = end.col - start.col;
int drow = end.row - start.row;
// It must be a vertical or horizontal bridge:
if (Math.abs(dcol) > 0 && Math.abs(drow) > 0) {
Log.d(getClass().getName(), "not a horizontal or vertical bridge.");
return false;
}
// First we check whether start and end elements can take the specified bridge counts.
int count_start = start.GetCurrentCount();
int count_end = end.GetCurrentCount();
if (count_start + count > start.max_connecting_bridges ||
count_end + count > end.max_connecting_bridges) {
Log.d(getClass().getName(), "This Bridge is not allowed");
return false;
}
Log.d(getClass().getName(),
String.format("Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row, start.col,
count_end, end.row, end.col));
Connection start_connection = null;
Connection end_connection = null;
// Next we check whether we are crossing any lines.
if (start.row == end.row) {
for (int i = (int) (start.col + Math.signum(dcol)); i != end.col; i += Math.signum(dcol)) {
if (getCurrentState().cell_occupied[start.row][i] > 0 &&
getCurrentState().cell_occupied[start.row][i] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
assert start.col != end.col;
if (start.col > end.col) {
start.connecting_east = GetOrCreateConnection(end, start.connecting_east);
end.connecting_west = GetOrCreateConnection(start, end.connecting_west);
start_connection = start.connecting_east;
end_connection = end.connecting_west;
} else {
start.connecting_west = GetOrCreateConnection(end, start.connecting_west);
end.connecting_east = GetOrCreateConnection(start, end.connecting_east);
start_connection = start.connecting_west;
end_connection = end.connecting_east;
}
} else {
assert start.col == end.col;
for (int i = (int) (start.row + Math.signum(drow)); i != end.row ; i += Math.signum(drow)) {
if (getCurrentState().cell_occupied[i][start.col] > 0 &&
getCurrentState().cell_occupied[i][start.col] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
if (start.row > end.row ) {
start.connecting_north = GetOrCreateConnection(end, start.connecting_north);
end.connecting_south = GetOrCreateConnection(start, end.connecting_south);
start_connection = start.connecting_north;
end_connection = end.connecting_south;
} else {
start.connecting_south= GetOrCreateConnection(end, start.connecting_south);
end.connecting_north = GetOrCreateConnection(start, end.connecting_north);
start_connection = start.connecting_south;
end_connection = end.connecting_north;
}
}
start_connection.destination = end;
end_connection.destination = start;
start_connection.second += count;
end_connection.second += count;
getCurrentState().AddToBridgeCache(start, end);
Log.d(getClass().getName(),
String.format("New bridge added. Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row,start.col,
count_end, end.row,end.col));
return true;
}
private Connection GetOrCreateConnection(
BoardElement end,
Connection connection) {
if (connection!= null) { return connection; }
return new Connection();
}
#TargetApi(Build.VERSION_CODES.N)
private void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
setCurrentState(new State(WIDTH_EASY));
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
System.out.println();
}
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
}
private void setCurrentState(State new_state) {
this.current_state = new_state;
}
public State getCurrentState() {
return current_state;
}
}
What algorithm could I use to make sure the Map can be Solved (Islands Connected with Bridges) before spawning the nodes.
This is what the map looks like (don't mind the design)
One thing to consider would be to start with a blank board. Place an island. Then place another island that can be connected to the first one (i.e. on one of the four cardinal directions). Connect the two with a bridge, and increment each island's count.
Now, pick one of the two islands and place another island that it can connect. Add the bridge and increment.
Continue in this way until you've placed the number of islands that you want to place.
The beauty here is that you start with an empty board, and during construction the board is always valid.
You'll have to ensure that you're not crossing bridges when you place new islands, but that's pretty easy to do, since you know where the existing bridges are.

Passing array of objects in java and saving the array of objects in the called method

I wrote some code to return me an array of objects. How do I save those objects in the called method?
public Ticket[] getOpenTicket() {
int ticketcount = 0;
for (int i = 0; i < ticket.length; i++) {
if (ticket[i] != null && ticket[i].getResolvedBy() == null) {
ticketcount = ticketcount + 1;
// System.out.println("Ticket raised by : " +
// ticket[i].getTicketno());
}
}
Ticket[] opentickets = new Ticket[ticketcount];
for (int i = 0; i < ticket.length; i++) {
if (ticket[i].getResolvedBy() == null) {
opentickets[i] = ticket[i];
}
}
return opentickets;
}
This is the called function from where I am calling openticket:
TicketDaoMemImpl tdmi=new TicketDaoMemImpl();
Ticket [] obj1=tdmi.getOpenTicket();
Thanks
Shouldn't that look more like this:
public class CheckTicket {
public Ticket [] openTicket() {
return arrayOfTickets; // wherever that comes from
}
}
CheckTicket cc = new CheckTicket();
Ticket[] t1 = cc.openTicket();
In this line of code
Ticket[] opentickets = new Ticket[ticketcount];
for (int i = 0; i < ticket.length; i++) {
if (ticket[i].getResolvedBy() == null) {
can't ticket[i] be null? It seems like that is most likely causing your issue - you call a method on what may be a null reference.
You should change you loop to something like:
Ticket[] opentickets = new Ticket[ticketcount];
int ticketIndex = 0;
for (int i = 0; i < ticket.length; i++) {
if (ticket[i] != null && ticket[i].getResolvedBy() == null) {
opentickets[ticketIndex] = ticket[i];
ticketIndex++;
}
}

null pointer exception, not going inside loop

The requirement is:If <bby:SaleTenderType> value is eCommerce , it reads the SalesOrderNum and calls the required function(appends other nodes to the root node). <bby:SaleTenderType> is not eCommerce, it should call other function.
The java code is as below:
//Added for giftCard
//error
Lineitems = retailChildren.item(j).getChildNodes();
for (int z1 = 0; z1 < Lineitems.getLength(); z1++) {
if (Lineitems.item(z1).getNodeName().equalsIgnoreCase("Return")) {
NodeList returnChild1 = Lineitems.item(z1).getChildNodes();
for (int z2 = 0; z2 < returnChild1.getLength(); z2++) {
if (returnChild1.item(z2).getNodeName().equalsIgnoreCase("Tender")) {
NodeList tenderChild = Lineitems.item(z2).getChildNodes(); //Null pointer exception
for (int z3 = 0; z3 < tenderChild.getLength(); z3++) {
if (tenderChild.item(z3).getNodeName().equalsIgnoreCase("bby:SaleTenderType")) {
System.out.println("Inside");
String SaleTenderType = tenderChild.item(z3).getFirstChild().getNodeValue();
if (SaleTenderType.equalsIgnoreCase("eCommerce")) {
Lineitems = retailChildren.item(j).getChildNodes();
for (int i2 = 0; i2 < Lineitems.getLength(); i2++) {
if (Lineitems.item(i2).getNodeName().equalsIgnoreCase("Return")) {
NodeList returnChild = Lineitems.item(i2).getChildNodes();
for (int k = 0; k < returnChild.getLength(); k++) {
if (returnChild.item(k).getNodeName().equalsIgnoreCase("c360:SalesOrder")) {
String POSLOGSalesOrderNo = returnChild.item(k).getFirstChild().getNodeValue();
SalesOrderNo = POSLOGSalesOrderNo.substring(2, 12);
String SalesOrderNum = POSLOGSalesOrderNo.substring(0, 2);
if (SalesOrderNum.equalsIgnoreCase("HD") || (SalesOrderNum.equalsIgnoreCase("SV")) || (SalesOrderNum.equalsIgnoreCase("CR")) || (SalesOrderNum.equalsIgnoreCase("CW"))) {
if (!prevSalesOrder.equals(SalesOrderNo)) {
IDocEl = outdoc.createElement("IDOC");
ORDERS05.appendChild(createIDocHeader_GC(POSLOGSalesOrderNo, outdoc, EMPST, IDocEl, StoreID, true, returnChild, TRANS));
prevSalesOrder = SalesOrderNo;
}
IDocEl.appendChild(createE1EDP01forReturnLineItem_GC(outdoc, returnChild, StoreID));
}
}
}
}
}
}
}
}
} else {
Lineitems = retailChildren.item(j).getChildNodes();
for (int i3 = 0; i3 < Lineitems.getLength(); i3++) {
if (Lineitems.item(i3).getNodeName().equalsIgnoreCase("Return")) {
NodeList returnChild = Lineitems.item(i3).getChildNodes();
for (int k = 0; k < returnChild.getLength(); k++) {
if (returnChild.item(k).getNodeName().equalsIgnoreCase("c360:SalesOrder")) {
String POSLOGSalesOrderNo = returnChild.item(k).getFirstChild().getNodeValue();
SalesOrderNo = POSLOGSalesOrderNo.substring(2, 12);
String SalesOrderNum = POSLOGSalesOrderNo.substring(0, 2);
if (SalesOrderNum.equalsIgnoreCase("HD") || (SalesOrderNum.equalsIgnoreCase("SV")) || (SalesOrderNum.equalsIgnoreCase("CR")) || (SalesOrderNum.equalsIgnoreCase("CW"))) {
if (!prevSalesOrder.equals(SalesOrderNo)) {
IDocEl = outdoc.createElement("IDOC");
ORDERS05.appendChild(createIDocHeader(POSLOGSalesOrderNo, outdoc, EMPST, IDocEl, StoreID, true, returnChild));
prevSalesOrder = SalesOrderNo;
}
IDocEl.appendChild(createE1EDP01forReturnLineItem(outdoc, returnChild, StoreID));
}
}
}
}
}
}
}
}
}
//end of gift card
Here I am reading root node <Return> then checking whether it contains <Tender> .. If <Tender> is present ( obviously <bby:SaleTenderType> will be present).. else if <Tender> is not present, then other function is done.
I am getting Null pointer exception in this line NodeList tenderChild = Lineitems.item(z2).getChildNodes();
Kindly provide your valuable inputs
Thanks in advance..

Categories