Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Currently i am getting data from my list but i get the data randomly, if anyone can help me to sort data on the basis of dayInNumber i have attached the picture of my database. I want to sort the data like 1 2 3 4 .. 14 enter image description here
Thanks
Suppose you have Client class defined as
class Client {
private long dayInNumber;
private String clientName;
private String day;
//setters and getters ommitted for brevity and clarity
}
Then you have a list of clients
List<Client> clients = new ArrayList<>();
To sort that dayInNumber you can either sort that in SQL (order by clause) assuming the data is coming from SQLite.
Or you can create a custom Comparator<T> of Client objects to do the sorting in code as below
import java.util.Comparator;
public class ClientDayInNumberComparator implements Comparator<Client> {
#Override
public int compare(Client c1, Client c2) {
if(c1.getDayInNumber() > c2.getDayInNumber()) return 1;
else if(c1.getDayInNumber() < c2.getDayInNumber()) return -1;
else
return 0;
}
}
This will sort clients by dayInNumber in ascending order (1, 2, 3,...N). Then use it as follows
List<Client> clients = new ArrayList<>();
Collections.sort(clients, new ClientDayInNumberComparator());
Collections is packed in java.utils package which you'll need to import
for sorting lists we can use sort(your_list) method of Collections class. This will sort the list as per the natural ordering i.e. ascending order. Since you want it sorted on the basis of a particular feature you should implement Comparator interface with type safety same as of your list. You will have to implement compareTo method. Refer to the below code for FYR:- `
public class Temp implements Comparable<Temp> {
Temp(int a, int b) {
this.a = a;
this.b = b;
}
int a;
int b;
public static void main(String[] args) {
Temp t1 = new Temp(11,2);
Temp t2 = new Temp(9,5);
Temp t3 = new Temp(1,7);
Temp t4 = new Temp(10,9);
Temp t5 = new Temp(14,11);
ArrayList<Temp> al = new ArrayList<Temp>();
al.add(t1);
al.add(t2);
al.add(t3);
al.add(t4);
al.add(t5);
Collections.sort(al);
for(Temp i:al) {
System.out.println(i.a+"," +i.b);
}
}
#Override
public int compareTo(Temp o) {
if(a==o.a) {
return 0;
}
else if(a>o.a) {
return 1;
}
else {
return -1;
}
}
}`
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 months ago.
Improve this question
I would like to pre-calculate a similarity score of a group of elements.
So if the group has three elements, A, B, C, then there are scores for similarity:
A,B: score1
A,C: score2
B,C: score3
C,B: score3
The relationship is symmetric, so f(B,A) is the same as f(A,B). I would like to do something like: HashMap<Pair<>, Score>, but so far of the tuple classes I have looked at, f(B,A).equals(f(A,B)) does not hold.
Is there a Pair tuples implementation where Pair(A,B) == Pair(B,A)?
As suggested, if you really wanted to you could use a Set, but much nicer to write your own, especially if you need to preserve the order of your two elements.
public class Eg {
public static void main(String[] args) {
Set<String> ab = new LinkedHashSet<String>(List.of("A", "B"));
Set<String> ba = new LinkedHashSet<String>(List.of("B", "A"));
System.out.println(ab.equals(ba));
System.out.println(ba.equals(ab));
System.out.println(ab.stream().findFirst().get());
System.out.println(ab.stream().skip(1).findFirst().get());
System.out.println(ba.stream().findFirst().get());
System.out.println(ba.stream().skip(1).findFirst().get());
MyTuple<String> mab = new MyTuple<>("A", "B");
MyTuple<String> mba = new MyTuple<>("B", "A");
System.out.println(mab.equals(mba));
System.out.println(mba.equals(mab));
}
public record MyTuple<T>(T first, T second) {
#Override
public boolean equals(Object o) {
return o instanceof MyTuple<?> other &&
((other.first.equals(first) && other.second.equals(second)) ||
(other.first.equals(second) && other.second.equals(first)));
}
#Override
public int hashCode() {
return Objects.hash(first, second);
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to change the loop to Java streams.
For example,
interface Logic {
int apply(int value);
}
public class AddOneLogic implements Logic {
#Override
public int apply(int value) {
return value + 1;
}
}
public class AddTwoLogic implements Logic {
#Override
public int apply(int value) {
return value + 2;
}
}
Using a loop to apply a Logic looks like
List<Logic> logics = new ArrayList<>();
logics.add(new AddOneLogic());
logics.add(new AddTwoLogic());
int init = 1;
I want to change to streams below. Is there any better way to do it?
int result = init;
for (Logic logic : logics) {
result = logic.apply(result);
}
As #duffymo mentioned in the comments, these classes aren't particularly useful and they could be replaced with Function<Integer, Integer>s and lambda expressions to define them.
In that case, you may want to reduce a list/stream of Functions by Function::andThen,
Function<Integer, Integer> addOneFunction = i -> i + 1;
Function<Integer, Integer> addTwoFunction = i -> i + 2;
Function<Integer, Integer> function =
Stream.of(addOneFunction, addTwoFunction)
.reduce(Function.identity(), Function::andThen);
so you would get a composed function to work with
Integer result = function.apply(init);
// ((1 + 1) + 2) = 4
You can do it with Stream and AtomicInteger and getAndSet(int) method as below,
AtomicInteger result = new AtomicInteger(1);
logics.stream().forEach(ele-> result.getAndSet(ele.apply(result.get())));
// result = ((1+1)+2)=4
Better option would be to use Function,
Function<Integer, Integer> addOne = i -> i + 1;
Function<Integer, Integer> addTwo = i -> i + 2;
List<Function<Integer, Integer>> logics = new ArrayList<>();
logics.add(addOne);
logics.add(addTwo);
AtomicInteger result = new AtomicInteger(1);
logics.stream().forEach(ele-> result.getAndSet(ele.apply(result.get())));
You can even avoid logics list and use andThen method as below,
Function<Integer, Integer> add = addOne.andThen(addTwo);
result = add.apply(1);
Hope it helps..!!
As others have already mentioned: The intention behind the question might be distorted by the attempt to simplify the question so that it can be posted here. The Logic interface does not really make sense, because it could be replaced with an IntUnaryOperator.
Not with a Function<Integer, Integer> - that's a different thing!
But I'll (also) make some assumptions when trying to answer the question:
The Logic interface is merely a placeholder for an interface that has to be retained in its current form
Several Logic instances can sensibly be combined in order to yield an new Logic
The goal is not to "apply streams for the streams sake", but to create sensible, usable classes and methods (and it's a pity that this is worth mentioning...)
If this is the case, then I'd suggest creating a CombinedLogic class that simply offers a method for combining several Logic objects to create the combined one.
It could also be a concrete class that internally stores a List<Logic>. This might be handy in order to modify a combined logic later, as in combinedLogic.setElement(42, new OtherLogic());. But a public class with a modifiable state should be thought through carefully...
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombinedLogicExample {
public static void main(String[] args) {
List<Logic> logics = new ArrayList<>();
logics.add(new AddOneLogic());
logics.add(new AddTwoLogic());
Logic combined = CombinedLogic.of(logics);
// Alternatively:
// Logic logic1 = new AddOneLogic();
// Logic logic2 = new AddTwoLogic();
// Logic combined = CombinedLogic.of(logic1, logic2);
int init = 1;
int result = combined.apply(init);
System.out.println(result);
}
}
class CombinedLogic {
static Logic of(Logic... logics) {
return of(Arrays.asList(logics));
}
static Logic of(Iterable<? extends Logic> logics) {
return a -> {
int result = a;
for (Logic logic : logics) {
result = logic.apply(result);
}
return result;
};
}
}
interface Logic {
int apply(int value);
}
class AddOneLogic implements Logic {
#Override
public int apply(int value) {
return value + 1;
}
}
class AddTwoLogic implements Logic {
#Override
public int apply(int value) {
return value + 2;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have the following class:
class A {
List<A> as;
}
I need to find max depth. For example, I can have this:
A firstA = new A();
A secondA = new A();
A thirdA = new A();
firstA.addA(secondA);
firstA.addA(thirdA);
secondA.addA(new A());
secondA.addA(new A());
I need to return 3.
I tried to do recursive method,
Using Java 8 streams:
class A {
List<A> as;
public int getDepth() {
return 1 + as.stream().mapToInt(A::getDepth).max().orElse(0);
}
}
If you're not familiar with streams, this can be interpreted as 'add 1 to maximum depth of all children or 0 if there are no children'.
If you can't change A you can still use this by passing A into the method:
public class MyClass {
public static int getDepth(A a) {
return 1 + a.as.stream().mapToInt(MyClass::getDepth).max().orElse(0);
}
}
Recursive depth-computing:
public static int computeDepth(A a)
{
int maxDepth = 0;
for(A innerA : a.getAs())
{
int depth = computeDepth(innerA);
if(depth > maxDepth)
maxDepth = depth;
}
return maxDepth + 1;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to sort the arraylist of Process objects. A Process has 2 parameters: startTime and duration. I want to sort the arraylist in ascending order in startTime and for the same startTime, I want to sort in ascending order in duration. How should I do that?
First, I'm assuming your Process class looks like this (plus other stuff):
public class Process{
private int startTime;
private int duration;
public int getStartTime(){
return startTime;
}
public int getDuration(){
return duration;
}
}
The first choice, the "default" sorting method for Processes is by the method you stated (first by startTime ascending, then by duration ascending), you could make Process implement Comparable<Process>:
public class Process implements Comparable<Process>{
private int startTime;
private int duration;
public int compareTo(Process other){
if(startTime < other.startTime) return -1;
if(startTime > other.startTime) return 1;
//If here, startTime == other.startTime
if(duration < other.duration) return -1;
if(duration > other.duration) return 1;
return 0;
}
}
Then you can sort an ArrayList<Process> using the simple method:
ArrayList<Process> a = new ArrayList<Process>();
//Fill up a with process instances
Collections.sort(a); //Sorts according to the compareTo method in Process.
If, however, this isn't going to be the default method of sorting Processes, (or you aren't able to make Process implement Comparable, then you're going to want to define a custom Comparator<Process> as follows:
class ProcessComparator implements Comparator<Process>{
public int compare(Process p1, Process p2){
if(p1.getStartTime() < p2.getStartTime()) return -1;
if(p1.getStartTime() > p2.getStartTime()) return 1;
//If here, p1.startTime == other.startTime
if(p1.getDuration() < p2.getDuration()) return -1;
if(p1.getDuration() > p2.getDuration()) return 1;
return 0;
}
}
Then, use one as such:
ArrayList<Process> a = new ArrayList<Process>();
//Fill up a with process instances
Collections.sort(a, new ProcessComparator()); //Sorts according to the compareTo method in Process.
You could to create a custom Comparator.
Or you could create reusable Comparators to help with future sorts. For example you can use the Bean Comparator which allows you to sort on a property of your Process object. The link contains example code for using the BeanComparator or for creating your own custom Comparator.
You can then use the Group Comparator, which allows you to sort on multiple properties at the same time.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is one of my class
class number11 {
String ab;
int i;
public number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
}
And in main method, I used
List<number11> n1= new ArrayList<number11>();
How can I access the value of integers and String contained in List? I do wish just to print them but to use further.
{Closed ,Thank you all}
Just loop over the list:
for (number11 n : list) {
String ab = n.ab;
int i = n.i;
//print ab and i
}
Note that number11 should be in CamelCase to follow Java's conventions: Number11.
From your question it seems you want list of your objects,
Before continuing, please create getters and setters, I've used them
Also your class name should be camelCase. Number11 is valid but not number11
You can fill the list using
List<number11> list = new ArrayList<number11>();
list.add(new number11("a",1));
list.add(new number11("b",2));
To access the members,
for (number11 n : list) {
String ab = n.getAb();
int i = n.getI();
}
like this
List<number11> n1= new ArrayList<number11>();
for(number11 n:n1){
System.out.println("String value: "+n.ab);
System.out.println("int value: "+n.i);
}
According to better coding standards.Follow the below rules
1.Change you class so that It starts with a camel case.
2.Change variables to private.
3.Add setter and getter methods
Assuming you have added values to the ArrayList you can read values by using code such as n1.get(0).ab or n1.get(0).i.
List l = new ArrayList<number11>();
l.add(new number11("x",1));
l.add(new number11("y",2));
for (number11 element : l) {
System.out.println(element.ab + " "+ element.i);
}
You might first want to add getter methods to your class number11.
e.g
public class number11{
String ab;
int i;
public number11(String ab,int i)
{
this.ab=ab;
this.i=i;
}
public int getI(){
return i;
}
public String getAb(){
return ab;
}
}
You need to obtain a reference to the particular object held inside the ArrayList via the get(index) method where index is the element number starting with 0. Simply call the getter methods to retrieve the values.
e.g
List<number11> n1= new ArrayList<number11>();
//Adding the object
n1.add(new number11("Test", 4));
//Retrieving the object.
number11 inst = n1.get(0);
//Retrieve and print the values
System.out.println(inst.getAb());
System.out.println(inst.getI());
For better convention change your class structure to,
class Number11 {
private String ab;
private int i;
public Number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
Access in this way.
List<number11> n1= new ArrayList<number11>();
if(n1!=null && n1.size()>0){
for (Number11 n : n1) {
String ab = n.getAb();
int i = n.getI();
//print ab and i
}
}
List<number11> n1= new ArrayList<number11>();
after adding values to this list n1 it will contains number11 type objects from index 0 to n-1, where n is number of element you added to list.
Then you can call what ever object as follows
n1.get(1) // this will return 2nd object in the list
It will contain ab and i
You can call them as follows
n1.get(1).getab // 2nd element ab value in list n1
n1.get(1).i // 2nd element i value in list n1
List Interface allows to:
Positional access — manipulates elements based on their numerical position in the list
MyClass obj = myList.get(24); //--get 25th item of a List<MyClass>--
Iteration access — extends Iterator semantics to take advantage of the list's sequential nature
for(MyClass obj : myList){ //-- go through all items of a List<MyClass> one by one--
int i = obj.someField;
}
Once you have your object, you can access its fields.