Home > front end >  Find the last element of a subset in a List
Find the last element of a subset in a List

Time:12-14

I have a list of objects with property a and b.

Property a is duplicated in the list of objects but not property b.

Therefore:

class MyObj {
   private String a;
   private String b;   
}

in my code:

MyObj obj1 = new MyObj();
obj1.setA("abc");  //duplicated
obj1.setB("b1");

MyObj obj2 = new MyObj();
obj2.setA("abc");  //duplicated 
obj2.setB("b2");

MyObj obj3 = new MyObj();
obj3.setA("def");  //Not duplicated
obj3.setB("b3");

myObjs obj1, obj2, obj3 are placed in a list, assuming they are sorted:

List <MyObj> objList = new ArrayList <> ();
objList.add(obj1);
objList.add(obj2);
objList.add(obj3);

Looping through objList, I want to stop at obj2, which is the last of abc and do something.

Here is what I tried:

for (int i = 0; i < objList.size(); i  ) {
   String thisA = objList.get(i).getA();
   String nextA = "";
   if (i < objList.size()-1){
      nextA = objList.get(i 1).getA();
   } else {
      nextA = "";
   }

   if (!thisA.equals(nextA)) {
       doSomething();
   }
}

Is there a more elegant solution to this, especially in Java 8 streams?

CodePudding user response:

Store the value of first object in the list in a variable and use Stream.takeWhile() which was introduced and is available for Java 9 and higher

String reference = objList.get(0).getA();

objList.stream()
       .takeWhile(obj -> reference.equals(obj.getA()))
       .forEach(obj -> doSomething());

CodePudding user response:

Actually yes, there is a more elegant way of doing it by using 'streams'. Here is an example of how you can modify your for loop:

List <MyObj> objList = new ArrayList <> ();

After defining your list group the objects:

Map<String, List<MyObj>> objGroups = objList.stream().collect(Collectors.groupingBy(MyObj::getA));

Then you can modify your for loop to a stream:

 objGroups.forEach((a, objs) -> {
                if (objs.size() > 1) {
                   // Your code goes here
                   // System.out.println("Duplicated: "   a);
                }
            });
  • Related