Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two sorted list of different types (String and Integer) in Java using Lambda

Merging the lists [“A”, “XYZ”, “AXTU”] and [2, 4, 6]

where the first list is sorted by word length. If a string length in the first list is the same as a number in the second list, the string comes first should produce like this:

[“A”, 2, “XYZ”, “AXTU”, 4, 6].

I tried like this:

Stream<String> stream = Stream.concat(list1.stream(), list2.stream().map(val -> Integer.toString(val)));
    System.out.println(stream.sorted().collect(Collectors.toList()));

and the output is like this:

[2, 4, 6, A, AXTU, XYZ]

Any idea to solve this problem? Thanks in advance. :)

like image 651
bgsudeep Avatar asked Feb 27 '26 15:02

bgsudeep


2 Answers

Somewhat simpler solution is to use Comparator.comparingInt:

List<Object> result = Stream
    .concat(list1.stream(), list2.stream())
    .sorted(Comparator.comparingInt(
        obj -> obj instanceof String ? 2 * ((String) obj).length() : 1 + 2 * (Integer) obj))
    .collect(Collectors.toList());
like image 87
Tagir Valeev Avatar answered Mar 01 '26 10:03

Tagir Valeev


The fact that your List(s) mix types (and given your conditional test is String length), I think you'll find it easiest to use a modifyable Collection and you'll need to iterate the first List continually. The fact that it's sorted doesn't help, since your merge criteria is length (for example, Z is one letter but the last lexically);

List<String> al = new ArrayList<>(Arrays.asList("A", "XYZ", "AXTU"));
List<Integer> bl = Arrays.asList(2, 4, 6);
List<String> merged = new ArrayList<>();
for (int len : bl) {
    Iterator<String> iter = al.iterator();
    while (iter.hasNext()) {
        String str = iter.next();
        if (str.length() <= len) {
            merged.add(str);
            iter.remove();
        }
    }
    merged.add(String.valueOf(len));
}
System.out.println(merged);

Output is (as requested)

[A, 2, XYZ, AXTU, 4, 6]
like image 20
Elliott Frisch Avatar answered Mar 01 '26 11:03

Elliott Frisch